Add Handler::getRouter()
[lhc/web/wiklou.git] / includes / Storage / SqlBlobStore.php
1 <?php
2 /**
3 * Service for storing and loading data blobs representing revision content.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * Attribution notice: when this file was created, much of its content was taken
21 * from the Revision.php file as present in release 1.30. Refer to the history
22 * of that file for original authorship.
23 *
24 * @file
25 */
26
27 namespace MediaWiki\Storage;
28
29 use DBAccessObjectUtils;
30 use ExternalStore;
31 use IDBAccessObject;
32 use IExpiringStore;
33 use InvalidArgumentException;
34 use Language;
35 use MWException;
36 use WANObjectCache;
37 use Wikimedia\Assert\Assert;
38 use Wikimedia\Rdbms\IDatabase;
39 use Wikimedia\Rdbms\ILoadBalancer;
40
41 /**
42 * Service for storing and loading Content objects.
43 *
44 * @since 1.31
45 *
46 * @note This was written to act as a drop-in replacement for the corresponding
47 * static methods in Revision.
48 */
49 class SqlBlobStore implements IDBAccessObject, BlobStore {
50
51 // Note: the name has been taken unchanged from the Revision class.
52 const TEXT_CACHE_GROUP = 'revisiontext:10';
53
54 /**
55 * @var ILoadBalancer
56 */
57 private $dbLoadBalancer;
58
59 /**
60 * @var WANObjectCache
61 */
62 private $cache;
63
64 /**
65 * @var bool|string Wiki ID
66 */
67 private $wikiId;
68
69 /**
70 * @var int
71 */
72 private $cacheExpiry = 604800; // 7 days
73
74 /**
75 * @var bool
76 */
77 private $compressBlobs = false;
78
79 /**
80 * @var bool|string
81 */
82 private $legacyEncoding = false;
83
84 /**
85 * @var Language|null
86 */
87 private $legacyEncodingConversionLang = null;
88
89 /**
90 * @var boolean
91 */
92 private $useExternalStore = false;
93
94 /**
95 * @param ILoadBalancer $dbLoadBalancer A load balancer for acquiring database connections
96 * @param WANObjectCache $cache A cache manager for caching blobs. This can be the local
97 * wiki's default instance even if $wikiId refers to a different wiki, since
98 * makeGlobalKey() is used to constructed a key that allows cached blobs from the
99 * same database to be re-used between wikis. For example, enwiki and frwiki will
100 * use the same cache keys for blobs from the wikidatawiki database, regardless of
101 * the cache's default key space.
102 * @param bool|string $wikiId The ID of the target wiki database. Use false for the local wiki.
103 */
104 public function __construct(
105 ILoadBalancer $dbLoadBalancer,
106 WANObjectCache $cache,
107 $wikiId = false
108 ) {
109 $this->dbLoadBalancer = $dbLoadBalancer;
110 $this->cache = $cache;
111 $this->wikiId = $wikiId;
112 }
113
114 /**
115 * @return int time for which blobs can be cached, in seconds
116 */
117 public function getCacheExpiry() {
118 return $this->cacheExpiry;
119 }
120
121 /**
122 * @param int $cacheExpiry time for which blobs can be cached, in seconds
123 */
124 public function setCacheExpiry( $cacheExpiry ) {
125 Assert::parameterType( 'integer', $cacheExpiry, '$cacheExpiry' );
126
127 $this->cacheExpiry = $cacheExpiry;
128 }
129
130 /**
131 * @return bool whether blobs should be compressed for storage
132 */
133 public function getCompressBlobs() {
134 return $this->compressBlobs;
135 }
136
137 /**
138 * @param bool $compressBlobs whether blobs should be compressed for storage
139 */
140 public function setCompressBlobs( $compressBlobs ) {
141 $this->compressBlobs = $compressBlobs;
142 }
143
144 /**
145 * @return false|string The legacy encoding to assume for blobs that are not marked as utf8.
146 * False means handling of legacy encoding is disabled, and utf8 assumed.
147 */
148 public function getLegacyEncoding() {
149 return $this->legacyEncoding;
150 }
151
152 /**
153 * @return Language|null The locale to use when decoding from a legacy encoding, or null
154 * if handling of legacy encoding is disabled.
155 */
156 public function getLegacyEncodingConversionLang() {
157 return $this->legacyEncodingConversionLang;
158 }
159
160 /**
161 * @param string $legacyEncoding The legacy encoding to assume for blobs that are
162 * not marked as utf8.
163 * @param Language $language The locale to use when decoding from a legacy encoding.
164 */
165 public function setLegacyEncoding( $legacyEncoding, Language $language ) {
166 Assert::parameterType( 'string', $legacyEncoding, '$legacyEncoding' );
167
168 $this->legacyEncoding = $legacyEncoding;
169 $this->legacyEncodingConversionLang = $language;
170 }
171
172 /**
173 * @return bool Whether to use the ExternalStore mechanism for storing blobs.
174 */
175 public function getUseExternalStore() {
176 return $this->useExternalStore;
177 }
178
179 /**
180 * @param bool $useExternalStore Whether to use the ExternalStore mechanism for storing blobs.
181 */
182 public function setUseExternalStore( $useExternalStore ) {
183 Assert::parameterType( 'boolean', $useExternalStore, '$useExternalStore' );
184
185 $this->useExternalStore = $useExternalStore;
186 }
187
188 /**
189 * @return ILoadBalancer
190 */
191 private function getDBLoadBalancer() {
192 return $this->dbLoadBalancer;
193 }
194
195 /**
196 * @param int $index A database index, like DB_MASTER or DB_REPLICA
197 *
198 * @return IDatabase
199 */
200 private function getDBConnection( $index ) {
201 $lb = $this->getDBLoadBalancer();
202 return $lb->getConnection( $index, [], $this->wikiId );
203 }
204
205 /**
206 * Stores an arbitrary blob of data and returns an address that can be used with
207 * getBlob() to retrieve the same blob of data,
208 *
209 * @param string $data
210 * @param array $hints An array of hints.
211 *
212 * @throws BlobAccessException
213 * @return string an address that can be used with getBlob() to retrieve the data.
214 */
215 public function storeBlob( $data, $hints = [] ) {
216 try {
217 $flags = $this->compressData( $data );
218
219 # Write to external storage if required
220 if ( $this->useExternalStore ) {
221 // Store and get the URL
222 $data = ExternalStore::insertToDefault( $data );
223 if ( $flags ) {
224 $flags .= ',';
225 }
226 $flags .= 'external';
227
228 // TODO: we could also return an address for the external store directly here.
229 // That would mean bypassing the text table entirely when the external store is
230 // used. We'll need to assess expected fallout before doing that.
231 }
232
233 $dbw = $this->getDBConnection( DB_MASTER );
234
235 $old_id = $dbw->nextSequenceValue( 'text_old_id_seq' );
236 $dbw->insert(
237 'text',
238 [
239 'old_id' => $old_id,
240 'old_text' => $data,
241 'old_flags' => $flags,
242 ],
243 __METHOD__
244 );
245
246 $textId = $dbw->insertId();
247
248 return self::makeAddressFromTextId( $textId );
249 } catch ( MWException $e ) {
250 throw new BlobAccessException( $e->getMessage(), 0, $e );
251 }
252 }
253
254 /**
255 * Retrieve a blob, given an address.
256 * Currently hardcoded to the 'text' table storage engine.
257 *
258 * MCR migration note: this replaces Revision::loadText
259 *
260 * @param string $blobAddress
261 * @param int $queryFlags
262 *
263 * @throws BlobAccessException
264 * @return string
265 */
266 public function getBlob( $blobAddress, $queryFlags = 0 ) {
267 Assert::parameterType( 'string', $blobAddress, '$blobAddress' );
268
269 // No negative caching; negative hits on text rows may be due to corrupted replica DBs
270 $blob = $this->cache->getWithSetCallback(
271 $this->getCacheKey( $blobAddress ),
272 $this->getCacheTTL(),
273 function ( $unused, &$ttl, &$setOpts ) use ( $blobAddress, $queryFlags ) {
274 // Ignore $setOpts; blobs are immutable and negatives are not cached
275 return $this->fetchBlob( $blobAddress, $queryFlags );
276 },
277 [ 'pcGroup' => self::TEXT_CACHE_GROUP, 'pcTTL' => IExpiringStore::TTL_PROC_LONG ]
278 );
279
280 if ( $blob === false ) {
281 throw new BlobAccessException( 'Failed to load blob from address ' . $blobAddress );
282 }
283
284 return $blob;
285 }
286
287 /**
288 * MCR migration note: this corresponds to Revision::fetchText
289 *
290 * @param string $blobAddress
291 * @param int $queryFlags
292 *
293 * @throws BlobAccessException
294 * @return string|false
295 */
296 private function fetchBlob( $blobAddress, $queryFlags ) {
297 list( $schema, $id, ) = self::splitBlobAddress( $blobAddress );
298
299 //TODO: MCR: also support 'ex' schema with ExternalStore URLs, plus flags encoded in the URL!
300 if ( $schema === 'tt' ) {
301 $textId = intval( $id );
302 } else {
303 // XXX: change to better exceptions! That makes migration more difficult, though.
304 throw new BlobAccessException( "Unknown blob address schema: $schema" );
305 }
306
307 if ( !$textId || $id !== (string)$textId ) {
308 // XXX: change to better exceptions! That makes migration more difficult, though.
309 throw new BlobAccessException( "Bad blob address: $blobAddress" );
310 }
311
312 // Callers doing updates will pass in READ_LATEST as usual. Since the text/blob tables
313 // do not normally get rows changed around, set READ_LATEST_IMMUTABLE in those cases.
314 $queryFlags |= DBAccessObjectUtils::hasFlags( $queryFlags, self::READ_LATEST )
315 ? self::READ_LATEST_IMMUTABLE
316 : 0;
317
318 list( $index, $options, $fallbackIndex, $fallbackOptions ) =
319 DBAccessObjectUtils::getDBOptions( $queryFlags );
320
321 // Text data is immutable; check replica DBs first.
322 $row = $this->getDBConnection( $index )->selectRow(
323 'text',
324 [ 'old_text', 'old_flags' ],
325 [ 'old_id' => $textId ],
326 __METHOD__,
327 $options
328 );
329
330 // Fallback to DB_MASTER in some cases if the row was not found, using the appropriate
331 // options, such as FOR UPDATE to avoid missing rows due to REPEATABLE-READ.
332 if ( !$row && $fallbackIndex !== null ) {
333 $row = $this->getDBConnection( $fallbackIndex )->selectRow(
334 'text',
335 [ 'old_text', 'old_flags' ],
336 [ 'old_id' => $textId ],
337 __METHOD__,
338 $fallbackOptions
339 );
340 }
341
342 if ( !$row ) {
343 wfWarn( __METHOD__ . ": No text row with ID $textId." );
344 return false;
345 }
346
347 $blob = $this->expandBlob( $row->old_text, $row->old_flags, $blobAddress );
348
349 if ( $blob === false ) {
350 wfLogWarning( __METHOD__ . ": Bad data in text row $textId." );
351 return false;
352 }
353
354 return $blob;
355 }
356
357 /**
358 * Get a cache key for a given Blob address.
359 *
360 * The cache key is constructed in a way that allows cached blobs from the same database
361 * to be re-used between wikis. For example, enwiki and frwiki will use the same cache keys
362 * for blobs from the wikidatawiki database.
363 *
364 * @param string $blobAddress
365 * @return string
366 */
367 private function getCacheKey( $blobAddress ) {
368 return $this->cache->makeGlobalKey(
369 'BlobStore',
370 'address',
371 $this->dbLoadBalancer->resolveDomainID( $this->wikiId ),
372 $blobAddress
373 );
374 }
375
376 /**
377 * Expand a raw data blob according to the flags given.
378 *
379 * MCR migration note: this replaces Revision::getRevisionText
380 *
381 * @note direct use is deprecated, use getBlob() or SlotRecord::getContent() instead.
382 * @todo make this private, there should be no need to use this method outside this class.
383 *
384 * @param string $raw The raw blob data, to be processed according to $flags.
385 * May be the blob itself, or the blob compressed, or just the address
386 * of the actual blob, depending on $flags.
387 * @param string|string[] $flags Blob flags, such as 'external' or 'gzip'.
388 * Note that not including 'utf-8' in $flags will cause the data to be decoded
389 * according to the legacy encoding specified via setLegacyEncoding.
390 * @param string|null $cacheKey A blob address for use in the cache key. If not given,
391 * caching is disabled.
392 *
393 * @return false|string The expanded blob or false on failure
394 */
395 public function expandBlob( $raw, $flags, $cacheKey = null ) {
396 if ( is_string( $flags ) ) {
397 $flags = explode( ',', $flags );
398 }
399
400 // Use external methods for external objects, text in table is URL-only then
401 if ( in_array( 'external', $flags ) ) {
402 $url = $raw;
403 $parts = explode( '://', $url, 2 );
404 if ( count( $parts ) == 1 || $parts[1] == '' ) {
405 return false;
406 }
407
408 if ( $cacheKey ) {
409 // The cached value should be decompressed, so handle that and return here.
410 return $this->cache->getWithSetCallback(
411 $this->getCacheKey( $cacheKey ),
412 $this->getCacheTTL(),
413 function () use ( $url, $flags ) {
414 // Ignore $setOpts; blobs are immutable and negatives are not cached
415 $blob = ExternalStore::fetchFromURL( $url, [ 'wiki' => $this->wikiId ] );
416
417 return $blob === false ? false : $this->decompressData( $blob, $flags );
418 },
419 [ 'pcGroup' => self::TEXT_CACHE_GROUP, 'pcTTL' => WANObjectCache::TTL_PROC_LONG ]
420 );
421 } else {
422 $blob = ExternalStore::fetchFromURL( $url, [ 'wiki' => $this->wikiId ] );
423 return $blob === false ? false : $this->decompressData( $blob, $flags );
424 }
425 } else {
426 return $this->decompressData( $raw, $flags );
427 }
428 }
429
430 /**
431 * If $wgCompressRevisions is enabled, we will compress data.
432 * The input string is modified in place.
433 * Return value is the flags field: contains 'gzip' if the
434 * data is compressed, and 'utf-8' if we're saving in UTF-8
435 * mode.
436 *
437 * MCR migration note: this replaces Revision::compressRevisionText
438 *
439 * @note direct use is deprecated!
440 * @todo make this private, there should be no need to use this method outside this class.
441 *
442 * @param mixed &$blob Reference to a text
443 *
444 * @return string
445 */
446 public function compressData( &$blob ) {
447 $blobFlags = [];
448
449 // Revisions not marked as UTF-8 will have legacy decoding applied by decompressData().
450 // XXX: if $this->legacyEncoding is not set, we could skip this. That would however be
451 // risky, since $this->legacyEncoding being set in the future would lead to data corruption.
452 $blobFlags[] = 'utf-8';
453
454 if ( $this->compressBlobs ) {
455 if ( function_exists( 'gzdeflate' ) ) {
456 $deflated = gzdeflate( $blob );
457
458 if ( $deflated === false ) {
459 wfLogWarning( __METHOD__ . ': gzdeflate() failed' );
460 } else {
461 $blob = $deflated;
462 $blobFlags[] = 'gzip';
463 }
464 } else {
465 wfDebug( __METHOD__ . " -- no zlib support, not compressing\n" );
466 }
467 }
468 return implode( ',', $blobFlags );
469 }
470
471 /**
472 * Re-converts revision text according to its flags.
473 *
474 * MCR migration note: this replaces Revision::decompressRevisionText
475 *
476 * @note direct use is deprecated, use getBlob() or SlotRecord::getContent() instead.
477 * @todo make this private, there should be no need to use this method outside this class.
478 *
479 * @param string $blob Blob in compressed/encoded form.
480 * @param array $blobFlags Compression flags, such as 'gzip'.
481 * Note that not including 'utf-8' in $blobFlags will cause the data to be decoded
482 * according to the legacy encoding specified via setLegacyEncoding.
483 *
484 * @return string|bool Decompressed text, or false on failure
485 */
486 public function decompressData( $blob, array $blobFlags ) {
487 // Revision::decompressRevisionText accepted false here, so defend against that
488 Assert::parameterType( 'string', $blob, '$blob' );
489
490 if ( in_array( 'error', $blobFlags ) ) {
491 // Error row, return false
492 return false;
493 }
494
495 if ( in_array( 'gzip', $blobFlags ) ) {
496 # Deal with optional compression of archived pages.
497 # This can be done periodically via maintenance/compressOld.php, and
498 # as pages are saved if $wgCompressRevisions is set.
499 $blob = gzinflate( $blob );
500
501 if ( $blob === false ) {
502 wfWarn( __METHOD__ . ': gzinflate() failed' );
503 return false;
504 }
505 }
506
507 if ( in_array( 'object', $blobFlags ) ) {
508 # Generic compressed storage
509 $obj = unserialize( $blob );
510 if ( !is_object( $obj ) ) {
511 // Invalid object
512 return false;
513 }
514 $blob = $obj->getText();
515 }
516
517 // Needed to support old revisions left over from from the 1.4 / 1.5 migration.
518 if ( $blob !== false && $this->legacyEncoding && $this->legacyEncodingConversionLang
519 && !in_array( 'utf-8', $blobFlags ) && !in_array( 'utf8', $blobFlags )
520 ) {
521 # Old revisions kept around in a legacy encoding?
522 # Upconvert on demand.
523 # ("utf8" checked for compatibility with some broken
524 # conversion scripts 2008-12-30)
525 $blob = $this->legacyEncodingConversionLang->iconv( $this->legacyEncoding, 'UTF-8', $blob );
526 }
527
528 return $blob;
529 }
530
531 /**
532 * Get the text cache TTL
533 *
534 * MCR migration note: this replaces Revision::getCacheTTL
535 *
536 * @return int
537 */
538 private function getCacheTTL() {
539 if ( $this->cache->getQoS( WANObjectCache::ATTR_EMULATION )
540 <= WANObjectCache::QOS_EMULATION_SQL
541 ) {
542 // Do not cache RDBMs blobs in...the RDBMs store
543 $ttl = WANObjectCache::TTL_UNCACHEABLE;
544 } else {
545 $ttl = $this->cacheExpiry ?: WANObjectCache::TTL_UNCACHEABLE;
546 }
547
548 return $ttl;
549 }
550
551 /**
552 * Returns an ID corresponding to the old_id field in the text table, corresponding
553 * to the given $address.
554 *
555 * Currently, $address must start with 'tt:' followed by a decimal integer representing
556 * the old_id; if $address does not start with 'tt:', null is returned. However,
557 * the implementation may change to insert rows into the text table on the fly.
558 * This implies that this method cannot be static.
559 *
560 * @note This method exists for use with the text table based storage schema.
561 * It should not be assumed that is will function with all future kinds of content addresses.
562 *
563 * @deprecated since 1.31, so don't assume that all blob addresses refer to a row in the text
564 * table. This method should become private once the relevant refactoring in WikiPage is
565 * complete.
566 *
567 * @param string $address
568 *
569 * @return int|null
570 */
571 public function getTextIdFromAddress( $address ) {
572 list( $schema, $id, ) = self::splitBlobAddress( $address );
573
574 if ( $schema !== 'tt' ) {
575 return null;
576 }
577
578 $textId = intval( $id );
579
580 if ( !$textId || $id !== (string)$textId ) {
581 throw new InvalidArgumentException( "Malformed text_id: $id" );
582 }
583
584 return $textId;
585 }
586
587 /**
588 * Returns an address referring to content stored in the text table row with the given ID.
589 * The address schema for blobs stored in the text table is "tt:" followed by an integer
590 * that corresponds to a value of the old_id field.
591 *
592 * @deprecated since 1.31. This method should become private once the relevant refactoring
593 * in WikiPage is complete.
594 *
595 * @param int $id
596 *
597 * @return string
598 */
599 public static function makeAddressFromTextId( $id ) {
600 return 'tt:' . $id;
601 }
602
603 /**
604 * Splits a blob address into three parts: the schema, the ID, and parameters/flags.
605 *
606 * @since 1.33
607 *
608 * @param string $address
609 *
610 * @throws InvalidArgumentException
611 * @return array [ $schema, $id, $parameters ], with $parameters being an assoc array.
612 */
613 public static function splitBlobAddress( $address ) {
614 if ( !preg_match( '/^(\w+):(\w+)(\?(.*))?$/', $address, $m ) ) {
615 throw new InvalidArgumentException( "Bad blob address: $address" );
616 }
617
618 $schema = strtolower( $m[1] );
619 $id = $m[2];
620 $parameters = isset( $m[4] ) ? wfCgiToArray( $m[4] ) : [];
621
622 return [ $schema, $id, $parameters ];
623 }
624
625 public function isReadOnly() {
626 if ( $this->useExternalStore && ExternalStore::defaultStoresAreReadOnly() ) {
627 return true;
628 }
629
630 return ( $this->getDBLoadBalancer()->getReadOnlyReason() !== false );
631 }
632 }