MediaWiki 1.40.4
SqlBlobStore.php
Go to the documentation of this file.
1<?php
26namespace MediaWiki\Storage;
27
28use AppendIterator;
33use InvalidArgumentException;
34use MWException;
35use StatusValue;
37use Wikimedia\Assert\Assert;
38use Wikimedia\AtEase\AtEase;
42
52
53 // Note: the name has been taken unchanged from the old Revision class.
54 public const TEXT_CACHE_GROUP = 'revisiontext:10';
55
59 private $dbLoadBalancer;
60
64 private $extStoreAccess;
65
69 private $cache;
70
74 private $dbDomain;
75
79 private $cacheExpiry = 604800; // 7 days
80
84 private $compressBlobs = false;
85
89 private $legacyEncoding = false;
90
94 private $useExternalStore = false;
95
107 public function __construct(
108 ILoadBalancer $dbLoadBalancer,
109 ExternalStoreAccess $extStoreAccess,
110 WANObjectCache $cache,
111 $dbDomain = false
112 ) {
113 $this->dbLoadBalancer = $dbLoadBalancer;
114 $this->extStoreAccess = $extStoreAccess;
115 $this->cache = $cache;
116 $this->dbDomain = $dbDomain;
117 }
118
122 public function getCacheExpiry() {
123 return $this->cacheExpiry;
124 }
125
129 public function setCacheExpiry( int $cacheExpiry ) {
130 $this->cacheExpiry = $cacheExpiry;
131 }
132
136 public function getCompressBlobs() {
137 return $this->compressBlobs;
138 }
139
143 public function setCompressBlobs( $compressBlobs ) {
144 $this->compressBlobs = $compressBlobs;
145 }
146
151 public function getLegacyEncoding() {
152 return $this->legacyEncoding;
153 }
154
163 public function setLegacyEncoding( string $legacyEncoding ) {
164 $this->legacyEncoding = $legacyEncoding;
165 }
166
170 public function getUseExternalStore() {
171 return $this->useExternalStore;
172 }
173
177 public function setUseExternalStore( bool $useExternalStore ) {
178 $this->useExternalStore = $useExternalStore;
179 }
180
184 private function getDBLoadBalancer() {
185 return $this->dbLoadBalancer;
186 }
187
193 private function getDBConnection( $index ) {
194 $lb = $this->getDBLoadBalancer();
195 return $lb->getConnectionRef( $index, [], $this->dbDomain );
196 }
197
208 public function storeBlob( $data, $hints = [] ) {
209 try {
210 $flags = $this->compressData( $data );
211
212 # Write to external storage if required
213 if ( $this->useExternalStore ) {
214 // Store and get the URL
215 $data = $this->extStoreAccess->insert( $data, [ 'domain' => $this->dbDomain ] );
216 if ( !$data ) {
217 throw new BlobAccessException( "Failed to store text to external storage" );
218 }
219 if ( $flags ) {
220 $flags .= ',';
221 }
222 $flags .= 'external';
223
224 // TODO: we could also return an address for the external store directly here.
225 // That would mean bypassing the text table entirely when the external store is
226 // used. We'll need to assess expected fallout before doing that.
227 }
228
229 $dbw = $this->getDBConnection( DB_PRIMARY );
230
231 $dbw->insert(
232 'text',
233 [ 'old_text' => $data, 'old_flags' => $flags ],
234 __METHOD__
235 );
236
237 $textId = $dbw->insertId();
238
239 return self::makeAddressFromTextId( $textId );
240 } catch ( MWException $e ) {
241 throw new BlobAccessException( $e->getMessage(), 0, $e );
242 }
243 }
244
257 public function getBlob( $blobAddress, $queryFlags = 0 ) {
258 Assert::parameterType( 'string', $blobAddress, '$blobAddress' );
259
260 $error = null;
261 $blob = $this->cache->getWithSetCallback(
262 $this->getCacheKey( $blobAddress ),
263 $this->getCacheTTL(),
264 function ( $unused, &$ttl, &$setOpts ) use ( $blobAddress, $queryFlags, &$error ) {
265 // Ignore $setOpts; blobs are immutable and negatives are not cached
266 [ $result, $errors ] = $this->fetchBlobs( [ $blobAddress ], $queryFlags );
267 // No negative caching; negative hits on text rows may be due to corrupted replica DBs
268 $error = $errors[$blobAddress] ?? null;
269 if ( $error ) {
270 $ttl = WANObjectCache::TTL_UNCACHEABLE;
271 }
272 return $result[$blobAddress];
273 },
274 $this->getCacheOptions()
275 );
276
277 if ( $error ) {
278 if ( $error[0] === 'badrevision' ) {
279 throw new BadBlobException( $error[1] );
280 } else {
281 throw new BlobAccessException( $error[1] );
282 }
283 }
284
285 Assert::postcondition( is_string( $blob ), 'Blob must not be null' );
286 return $blob;
287 }
288
300 public function getBlobBatch( $blobAddresses, $queryFlags = 0 ) {
301 // FIXME: All caching has temporarily been removed in I94c6f9ba7b9caeeb due to T235188.
302 // Caching behavior should be restored by reverting I94c6f9ba7b9caeeb as soon as
303 // the root cause of T235188 has been resolved.
304
305 [ $blobsByAddress, $errors ] = $this->fetchBlobs( $blobAddresses, $queryFlags );
306
307 $blobsByAddress = array_map( static function ( $blob ) {
308 return $blob === false ? null : $blob;
309 }, $blobsByAddress );
310
311 $result = StatusValue::newGood( $blobsByAddress );
312 foreach ( $errors as $error ) {
313 // @phan-suppress-next-line PhanParamTooFewUnpack
314 $result->warning( ...$error );
315 }
316 return $result;
317 }
318
333 private function fetchBlobs( $blobAddresses, $queryFlags ) {
334 $textIdToBlobAddress = [];
335 $result = [];
336 $errors = [];
337 foreach ( $blobAddresses as $blobAddress ) {
338 try {
339 [ $schema, $id ] = self::splitBlobAddress( $blobAddress );
340 } catch ( InvalidArgumentException $ex ) {
341 throw new BlobAccessException(
342 $ex->getMessage() . '. Use findBadBlobs.php to remedy.',
343 0,
344 $ex
345 );
346 }
347
348 // TODO: MCR: also support 'ex' schema with ExternalStore URLs, plus flags encoded in the URL!
349 if ( $schema === 'bad' ) {
350 // Database row was marked as "known bad"
351 wfDebug(
352 __METHOD__
353 . ": loading known-bad content ($blobAddress), returning empty string"
354 );
355 $result[$blobAddress] = '';
356 $errors[$blobAddress] = [
357 'badrevision',
358 'The content of this revision is missing or corrupted (bad schema)'
359 ];
360 } elseif ( $schema === 'tt' ) {
361 $textId = intval( $id );
362
363 if ( $textId < 1 || $id !== (string)$textId ) {
364 $errors[$blobAddress] = [
365 'internalerror',
366 "Bad blob address: $blobAddress. Use findBadBlobs.php to remedy."
367 ];
368 $result[$blobAddress] = false;
369 }
370
371 $textIdToBlobAddress[$textId] = $blobAddress;
372 } else {
373 $errors[$blobAddress] = [
374 'internalerror',
375 "Unknown blob address schema: $schema. Use findBadBlobs.php to remedy."
376 ];
377 $result[$blobAddress] = false;
378 }
379 }
380
381 $textIds = array_keys( $textIdToBlobAddress );
382 if ( !$textIds ) {
383 return [ $result, $errors ];
384 }
385 // Callers doing updates will pass in READ_LATEST as usual. Since the text/blob tables
386 // do not normally get rows changed around, set READ_LATEST_IMMUTABLE in those cases.
387 $queryFlags |= DBAccessObjectUtils::hasFlags( $queryFlags, self::READ_LATEST )
388 ? self::READ_LATEST_IMMUTABLE
389 : 0;
390 [ $index, $options, $fallbackIndex, $fallbackOptions ] =
392 // Text data is immutable; check replica DBs first.
393 $dbConnection = $this->getDBConnection( $index );
394 $rows = $dbConnection->select(
395 'text',
396 [ 'old_id', 'old_text', 'old_flags' ],
397 [ 'old_id' => $textIds ],
398 __METHOD__,
399 $options
400 );
401 $numRows = 0;
402 if ( $rows instanceof IResultWrapper ) {
403 $numRows = $rows->numRows();
404 }
405
406 // Fallback to DB_PRIMARY in some cases if not all the rows were found, using the appropriate
407 // options, such as FOR UPDATE to avoid missing rows due to REPEATABLE-READ.
408 if ( $numRows !== count( $textIds ) && $fallbackIndex !== null ) {
409 $fetchedTextIds = [];
410 foreach ( $rows as $row ) {
411 $fetchedTextIds[] = $row->old_id;
412 }
413 $missingTextIds = array_diff( $textIds, $fetchedTextIds );
414 $dbConnection = $this->getDBConnection( $fallbackIndex );
415 $rowsFromFallback = $dbConnection->select(
416 'text',
417 [ 'old_id', 'old_text', 'old_flags' ],
418 [ 'old_id' => $missingTextIds ],
419 __METHOD__,
420 $fallbackOptions
421 );
422 $appendIterator = new AppendIterator();
423 $appendIterator->append( $rows );
424 $appendIterator->append( $rowsFromFallback );
425 $rows = $appendIterator;
426 }
427
428 foreach ( $rows as $row ) {
429 $blobAddress = $textIdToBlobAddress[$row->old_id];
430 $blob = false;
431 if ( $row->old_text !== null ) {
432 $blob = $this->expandBlob( $row->old_text, $row->old_flags, $blobAddress );
433 }
434 if ( $blob === false ) {
435 $errors[$blobAddress] = [
436 'internalerror',
437 "Bad data in text row {$row->old_id}. Use findBadBlobs.php to remedy."
438 ];
439 }
440 $result[$blobAddress] = $blob;
441 }
442
443 // If we're still missing some of the rows, set errors for missing blobs.
444 if ( count( $result ) !== count( $blobAddresses ) ) {
445 foreach ( $blobAddresses as $blobAddress ) {
446 if ( !isset( $result[$blobAddress ] ) ) {
447 $errors[$blobAddress] = [
448 'internalerror',
449 "Unable to fetch blob at $blobAddress. Use findBadBlobs.php to remedy."
450 ];
451 $result[$blobAddress] = false;
452 }
453 }
454 }
455 return [ $result, $errors ];
456 }
457
468 private function getCacheKey( $blobAddress ) {
469 return $this->cache->makeGlobalKey(
470 'SqlBlobStore-blob',
471 $this->dbLoadBalancer->resolveDomainID( $this->dbDomain ),
472 $blobAddress
473 );
474 }
475
481 private function getCacheOptions() {
482 return [
483 'pcGroup' => self::TEXT_CACHE_GROUP,
484 'pcTTL' => WANObjectCache::TTL_PROC_LONG,
485 'segmentable' => true
486 ];
487 }
488
509 public function expandBlob( $raw, $flags, $blobAddress = null ) {
510 if ( is_string( $flags ) ) {
511 $flags = self::explodeFlags( $flags );
512 }
513 if ( in_array( 'error', $flags ) ) {
514 throw new BadBlobException(
515 "The content of this revision is missing or corrupted (error flag)"
516 );
517 }
518
519 // Use external methods for external objects, text in table is URL-only then
520 if ( in_array( 'external', $flags ) ) {
521 $url = $raw;
522 $parts = explode( '://', $url, 2 );
523 if ( count( $parts ) == 1 || $parts[1] == '' ) {
524 return false;
525 }
526
527 if ( $blobAddress ) {
528 // The cached value should be decompressed, so handle that and return here.
529 return $this->cache->getWithSetCallback(
530 $this->getCacheKey( $blobAddress ),
531 $this->getCacheTTL(),
532 function () use ( $url, $flags ) {
533 // Ignore $setOpts; blobs are immutable and negatives are not cached
534 $blob = $this->extStoreAccess
535 ->fetchFromURL( $url, [ 'domain' => $this->dbDomain ] );
536
537 return $blob === false ? false : $this->decompressData( $blob, $flags );
538 },
539 $this->getCacheOptions()
540 );
541 } else {
542 $blob = $this->extStoreAccess->fetchFromURL( $url, [ 'domain' => $this->dbDomain ] );
543 return $blob === false ? false : $this->decompressData( $blob, $flags );
544 }
545 } else {
546 return $this->decompressData( $raw, $flags );
547 }
548 }
549
566 public function compressData( &$blob ) {
567 $blobFlags = [];
568
569 // Revisions not marked as UTF-8 will have legacy decoding applied by decompressData().
570 // XXX: if $this->legacyEncoding is not set, we could skip this. That would however be
571 // risky, since $this->legacyEncoding being set in the future would lead to data corruption.
572 $blobFlags[] = 'utf-8';
573
574 if ( $this->compressBlobs ) {
575 if ( function_exists( 'gzdeflate' ) ) {
576 $deflated = gzdeflate( $blob );
577
578 if ( $deflated === false ) {
579 wfLogWarning( __METHOD__ . ': gzdeflate() failed' );
580 } else {
581 $blob = $deflated;
582 $blobFlags[] = 'gzip';
583 }
584 } else {
585 wfDebug( __METHOD__ . " -- no zlib support, not compressing" );
586 }
587 }
588 return implode( ',', $blobFlags );
589 }
590
606 public function decompressData( string $blob, array $blobFlags ) {
607 if ( in_array( 'error', $blobFlags ) ) {
608 // Error row, return false
609 return false;
610 }
611
612 if ( in_array( 'gzip', $blobFlags ) ) {
613 # Deal with optional compression of archived pages.
614 # This can be done periodically via maintenance/compressOld.php, and
615 # as pages are saved if $wgCompressRevisions is set.
616 $blob = gzinflate( $blob );
617
618 if ( $blob === false ) {
619 wfWarn( __METHOD__ . ': gzinflate() failed' );
620 return false;
621 }
622 }
623
624 if ( in_array( 'object', $blobFlags ) ) {
625 # Generic compressed storage
627 if ( !$obj ) {
628 // Invalid object
629 return false;
630 }
631 $blob = $obj->getText();
632 }
633
634 // Needed to support old revisions from before MW 1.5.
635 if ( $blob !== false && $this->legacyEncoding
636 && !in_array( 'utf-8', $blobFlags ) && !in_array( 'utf8', $blobFlags )
637 ) {
638 # Old revisions kept around in a legacy encoding?
639 # Upconvert on demand.
640 # ("utf8" checked for compatibility with some broken
641 # conversion scripts 2008-12-30)
642 # Even with //IGNORE iconv can whine about illegal characters in
643 # *input* string. We just ignore those too.
644 # REF: https://bugs.php.net/bug.php?id=37166
645 # REF: https://phabricator.wikimedia.org/T18885
646 AtEase::suppressWarnings();
647 $blob = iconv( $this->legacyEncoding, 'UTF-8//IGNORE', $blob );
648 AtEase::restoreWarnings();
649 }
650
651 return $blob;
652 }
653
661 private function getCacheTTL() {
662 $cache = $this->cache;
663
664 if ( $cache->getQoS( $cache::ATTR_DURABILITY ) >= $cache::QOS_DURABILITY_RDBMS ) {
665 // Do not cache RDBMs blobs in...the RDBMs store
666 $ttl = $cache::TTL_UNCACHEABLE;
667 } else {
668 $ttl = $this->cacheExpiry ?: $cache::TTL_UNCACHEABLE;
669 }
670
671 return $ttl;
672 }
673
694 public function getTextIdFromAddress( $address ) {
695 [ $schema, $id, ] = self::splitBlobAddress( $address );
696
697 if ( $schema !== 'tt' ) {
698 return null;
699 }
700
701 $textId = intval( $id );
702
703 if ( !$textId || $id !== (string)$textId ) {
704 throw new InvalidArgumentException( "Malformed text_id: $id" );
705 }
706
707 return $textId;
708 }
709
723 public static function makeAddressFromTextId( $id ) {
724 return 'tt:' . $id;
725 }
726
733 public static function explodeFlags( string $flagsString ) {
734 return $flagsString === '' ? [] : explode( ',', $flagsString );
735 }
736
747 public static function splitBlobAddress( $address ) {
748 if ( !preg_match( '/^([-+.\w]+):([^\s?]+)(\?([^\s]*))?$/', $address, $m ) ) {
749 throw new InvalidArgumentException( "Bad blob address: $address" );
750 }
751
752 $schema = strtolower( $m[1] );
753 $id = $m[2];
754 $parameters = wfCgiToArray( $m[4] ?? '' );
755
756 return [ $schema, $id, $parameters ];
757 }
758
759 public function isReadOnly() {
760 if ( $this->useExternalStore && $this->extStoreAccess->isReadOnly() ) {
761 return true;
762 }
763
764 return ( $this->getDBLoadBalancer()->getReadOnlyReason() !== false );
765 }
766}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
wfCgiToArray( $query)
This is the logical opposite of wfArrayToCgi(): it accepts a query string as its argument and returns...
Helper class for DAO classes.
static getDBOptions( $bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
static hasFlags( $bitfield, $flags)
This is the main interface for fetching or inserting objects with ExternalStore.
static unserialize(string $str, bool $allowDouble=false)
Unserialize a HistoryBlob.
MediaWiki exception.
Exception thrown when a blob has the "bad" content address schema, or has "error" in its old_flags,...
Exception representing a failure to access a data blob.
Service for storing and loading Content objects representing revision data blobs.
static makeAddressFromTextId( $id)
Returns an address referring to content stored in the text table row with the given ID.
getTextIdFromAddress( $address)
Returns an ID corresponding to the old_id field in the text table, corresponding to the given $addres...
__construct(ILoadBalancer $dbLoadBalancer, ExternalStoreAccess $extStoreAccess, WANObjectCache $cache, $dbDomain=false)
decompressData(string $blob, array $blobFlags)
Re-converts revision text according to its flags.
getBlob( $blobAddress, $queryFlags=0)
Retrieve a blob, given an address.
setLegacyEncoding(string $legacyEncoding)
Set the legacy encoding to assume for blobs that do not have the utf-8 flag set.
compressData(&$blob)
If $wgCompressRevisions is enabled, we will compress data.
static splitBlobAddress( $address)
Splits a blob address into three parts: the schema, the ID, and parameters/flags.
getBlobBatch( $blobAddresses, $queryFlags=0)
A batched version of BlobStore::getBlob.
storeBlob( $data, $hints=[])
Stores an arbitrary blob of data and returns an address that can be used with getBlob() to retrieve t...
setUseExternalStore(bool $useExternalStore)
isReadOnly()
Check if the blob metadata or backing blob data store is read-only.
expandBlob( $raw, $flags, $blobAddress=null)
Expand a raw data blob according to the flags given.
static explodeFlags(string $flagsString)
Split a comma-separated old_flags value into its constituent parts.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Multi-datacenter aware caching interface.
Interface for database access objects.
Service for loading and storing data blobs.
Definition BlobStore.php:33
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:36
This class is a delegate to ILBFactory for a given database cluster.
Result wrapper for grabbing data queried from an IDatabase object.
const DB_PRIMARY
Definition defines.php:28
return true
Definition router.php:92