3 * Efficient concatenated text storage.
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.
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.
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
24 * Base class for general text storage via the "object" flag in old_flags, or
25 * two-part external storage URLs. Used for represent efficient concatenated
26 * storage, and migration-related pointer objects.
28 interface HistoryBlob
{
30 * Adds an item of text, returns a stub object which points to the item.
31 * You must call setLocation() on the stub object before storing it to the
36 * @return string The key for getItem()
38 function addItem( $text );
41 * Get item by key, or false if the key is not present
47 function getItem( $key );
50 * Set the "default text"
51 * This concept is an odd property of the current DB schema, whereby each text item has a revision
52 * associated with it. The default text is the text of the associated revision. There may, however,
53 * be other revisions in the same object.
55 * Default text is not required for two-part external storage URLs.
59 function setText( $text );
62 * Get default text. This is called from Revision::getRevisionText()
70 * Concatenated gzip (CGZ) storage
71 * Improves compression ratio by concatenating like objects before gzipping
73 class ConcatenatedGzipHistoryBlob
implements HistoryBlob
{
74 public $mVersion = 0, $mCompressed = false, $mItems = [], $mDefaultHash = '';
76 public $mMaxSize = 10000000;
77 public $mMaxCount = 100;
79 public function __construct() {
80 if ( !function_exists( 'gzdeflate' ) ) {
81 throw new MWException( "Need zlib support to read or write this "
82 . "kind of history object (ConcatenatedGzipHistoryBlob)\n" );
90 public function addItem( $text ) {
93 if ( !isset( $this->mItems
[$hash] ) ) {
94 $this->mItems
[$hash] = $text;
95 $this->mSize +
= strlen( $text );
101 * @param string $hash
104 public function getItem( $hash ) {
106 if ( array_key_exists( $hash, $this->mItems
) ) {
107 return $this->mItems
[$hash];
114 * @param string $text
117 public function setText( $text ) {
119 $this->mDefaultHash
= $this->addItem( $text );
125 public function getText() {
127 return $this->getItem( $this->mDefaultHash
);
133 * @param string $hash
135 public function removeItem( $hash ) {
136 $this->mSize
-= strlen( $this->mItems
[$hash] );
137 unset( $this->mItems
[$hash] );
141 * Compress the bulk data in the object
143 public function compress() {
144 if ( !$this->mCompressed
) {
145 $this->mItems
= gzdeflate( serialize( $this->mItems
) );
146 $this->mCompressed
= true;
151 * Uncompress bulk data
153 public function uncompress() {
154 if ( $this->mCompressed
) {
155 $this->mItems
= unserialize( gzinflate( $this->mItems
) );
156 $this->mCompressed
= false;
165 return [ 'mVersion', 'mCompressed', 'mItems', 'mDefaultHash' ];
168 function __wakeup() {
173 * Helper function for compression jobs
174 * Returns true until the object is "full" and ready to be committed
178 public function isHappy() {
179 return $this->mSize
< $this->mMaxSize
180 && count( $this->mItems
) < $this->mMaxCount
;
185 * Pointer object for an item within a CGZ blob stored in the text table.
187 class HistoryBlobStub
{
189 * @var array One-step cache variable to hold base blobs; operations that
190 * pull multiple revisions may often pull multiple times from the same
191 * blob. By keeping the last-used one open, we avoid redundant
192 * unserialization and decompression overhead.
194 protected static $blobCache = [];
206 * @param string $hash The content hash of the text
207 * @param int $oldid The old_id for the CGZ object
209 function __construct( $hash = '', $oldid = 0 ) {
210 $this->mHash
= $hash;
214 * Sets the location (old_id) of the main object to which this object
218 function setLocation( $id ) {
223 * Sets the location (old_id) of the referring object
226 function setReferrer( $id ) {
231 * Gets the location of the referring object
234 function getReferrer() {
239 * @return string|false
242 if ( isset( self
::$blobCache[$this->mOldId
] ) ) {
243 $obj = self
::$blobCache[$this->mOldId
];
245 $dbr = wfGetDB( DB_REPLICA
);
246 $row = $dbr->selectRow(
248 [ 'old_flags', 'old_text' ],
249 [ 'old_id' => $this->mOldId
]
256 $flags = explode( ',', $row->old_flags
);
257 if ( in_array( 'external', $flags ) ) {
258 $url = $row->old_text
;
259 $parts = explode( '://', $url, 2 );
260 if ( !isset( $parts[1] ) ||
$parts[1] == '' ) {
263 $row->old_text
= ExternalStore
::fetchFromURL( $url );
267 if ( !in_array( 'object', $flags ) ) {
271 if ( in_array( 'gzip', $flags ) ) {
272 // This shouldn't happen, but a bug in the compress script
273 // may at times gzip-compress a HistoryBlob object row.
274 $obj = unserialize( gzinflate( $row->old_text
) );
276 $obj = unserialize( $row->old_text
);
279 if ( !is_object( $obj ) ) {
280 // Correct for old double-serialization bug.
281 $obj = unserialize( $obj );
284 // Save this item for reference; if pulling many
285 // items in a row we'll likely use it again.
287 self
::$blobCache = [ $this->mOldId
=> $obj ];
290 return $obj->getItem( $this->mHash
);
294 * Get the content hash
304 * To speed up conversion from 1.4 to 1.5 schema, text rows can refer to the
305 * leftover cur table as the backend. This avoids expensively copying hundreds
306 * of megabytes of data during the conversion downtime.
308 * Serialized HistoryBlobCurStub objects will be inserted into the text table
309 * on conversion if $wgLegacySchemaConversion is set to true.
311 class HistoryBlobCurStub
{
316 * @param int $curid The cur_id pointed to
318 function __construct( $curid = 0 ) {
319 $this->mCurId
= $curid;
323 * Sets the location (cur_id) of the main object to which this object
328 function setLocation( $id ) {
333 * @return string|bool
336 $dbr = wfGetDB( DB_REPLICA
);
337 $row = $dbr->selectRow( 'cur', [ 'cur_text' ], [ 'cur_id' => $this->mCurId
] );
341 return $row->cur_text
;
346 * Diff-based history compression
347 * Requires xdiff 1.5+ and zlib
349 class DiffHistoryBlob
implements HistoryBlob
{
350 /** @var array Uncompressed item cache */
353 /** @var int Total uncompressed size */
357 * @var array Array of diffs. If a diff D from A to B is notated D = B - A,
358 * and Z is an empty string:
360 * { item[map[i]] - item[map[i-1]] where i > 0
362 * { item[map[i]] - Z where i = 0
366 /** @var array The diff map, see above */
369 /** @var int The key for getText()
373 /** @var string Compressed storage */
376 /** @var bool True if the object is locked against further writes */
377 public $mFrozen = false;
380 * @var int The maximum uncompressed size before the object becomes sad
381 * Should be less than max_allowed_packet
383 public $mMaxSize = 10000000;
385 /** @var int The maximum number of text items before the object becomes sad */
386 public $mMaxCount = 100;
388 /** Constants from xdiff.h */
389 const XDL_BDOP_INS
= 1;
390 const XDL_BDOP_CPY
= 2;
391 const XDL_BDOP_INSB
= 3;
393 function __construct() {
394 if ( !function_exists( 'gzdeflate' ) ) {
395 throw new MWException( "Need zlib support to read or write DiffHistoryBlob\n" );
400 * @throws MWException
401 * @param string $text
404 function addItem( $text ) {
405 if ( $this->mFrozen
) {
406 throw new MWException( __METHOD__
. ": Cannot add more items after sleep/wakeup" );
409 $this->mItems
[] = $text;
410 $this->mSize +
= strlen( $text );
411 $this->mDiffs
= null; // later
412 return count( $this->mItems
) - 1;
419 function getItem( $key ) {
420 return $this->mItems
[$key];
424 * @param string $text
426 function setText( $text ) {
427 $this->mDefaultKey
= $this->addItem( $text );
434 return $this->getItem( $this->mDefaultKey
);
438 * @throws MWException
440 function compress() {
441 if ( !function_exists( 'xdiff_string_rabdiff' ) ) {
442 throw new MWException( "Need xdiff 1.5+ support to write DiffHistoryBlob\n" );
444 if ( isset( $this->mDiffs
) ) {
445 // Already compressed
448 if ( !count( $this->mItems
) ) {
453 // Create two diff sequences: one for main text and one for small text
468 $mItemsCount = count( $this->mItems
);
469 for ( $i = 0; $i < $mItemsCount; $i++
) {
470 $text = $this->mItems
[$i];
474 $mainTail = $sequences['main']['tail'];
475 if ( strlen( $text ) < strlen( $mainTail ) * $smallFactor ) {
481 $seq =& $sequences[$seqName];
482 $tail = $seq['tail'];
483 $diff = $this->diff( $tail, $text );
484 $seq['diffs'][] = $diff;
486 $seq['tail'] = $text;
488 unset( $seq ); // unlink dangerous alias
490 // Knit the sequences together
493 $this->mDiffMap
= [];
494 foreach ( $sequences as $seq ) {
495 if ( !count( $seq['diffs'] ) ) {
498 if ( $tail === '' ) {
499 $this->mDiffs
[] = $seq['diffs'][0];
501 $head = $this->patch( '', $seq['diffs'][0] );
502 $this->mDiffs
[] = $this->diff( $tail, $head );
504 $this->mDiffMap
[] = $seq['map'][0];
505 $diffsCount = count( $seq['diffs'] );
506 for ( $i = 1; $i < $diffsCount; $i++
) {
507 $this->mDiffs
[] = $seq['diffs'][$i];
508 $this->mDiffMap
[] = $seq['map'][$i];
510 $tail = $seq['tail'];
519 function diff( $t1, $t2 ) {
520 # Need to do a null concatenation with warnings off, due to bugs in the current version of xdiff
521 # "String is not zero-terminated"
522 MediaWiki\
suppressWarnings();
523 $diff = xdiff_string_rabdiff( $t1, $t2 ) . '';
524 MediaWiki\restoreWarnings
();
529 * @param string $base
530 * @param string $diff
531 * @return bool|string
533 function patch( $base, $diff ) {
534 if ( function_exists( 'xdiff_string_bpatch' ) ) {
535 MediaWiki\
suppressWarnings();
536 $text = xdiff_string_bpatch( $base, $diff ) . '';
537 MediaWiki\restoreWarnings
();
541 # Pure PHP implementation
543 $header = unpack( 'Vofp/Vcsize', substr( $diff, 0, 8 ) );
545 # Check the checksum if hash extension is available
546 $ofp = $this->xdiffAdler32( $base );
547 if ( $ofp !== false && $ofp !== substr( $diff, 0, 4 ) ) {
548 wfDebug( __METHOD__
. ": incorrect base checksum\n" );
551 if ( $header['csize'] != strlen( $base ) ) {
552 wfDebug( __METHOD__
. ": incorrect base length\n" );
558 while ( $p < strlen( $diff ) ) {
559 $x = unpack( 'Cop', substr( $diff, $p, 1 ) );
563 case self
::XDL_BDOP_INS
:
564 $x = unpack( 'Csize', substr( $diff, $p, 1 ) );
566 $out .= substr( $diff, $p, $x['size'] );
569 case self
::XDL_BDOP_INSB
:
570 $x = unpack( 'Vcsize', substr( $diff, $p, 4 ) );
572 $out .= substr( $diff, $p, $x['csize'] );
575 case self
::XDL_BDOP_CPY
:
576 $x = unpack( 'Voff/Vcsize', substr( $diff, $p, 8 ) );
578 $out .= substr( $base, $x['off'], $x['csize'] );
581 wfDebug( __METHOD__
. ": invalid op\n" );
589 * Compute a binary "Adler-32" checksum as defined by LibXDiff, i.e. with
590 * the bytes backwards and initialised with 0 instead of 1. See T36428.
593 * @return string|bool False if the hash extension is not available
595 function xdiffAdler32( $s ) {
596 if ( !function_exists( 'hash' ) ) {
601 if ( $init === null ) {
602 $init = str_repeat( "\xf0", 205 ) . "\xee" . str_repeat( "\xf0", 67 ) . "\x02";
605 // The real Adler-32 checksum of $init is zero, so it initialises the
606 // state to zero, as it is at the start of LibXDiff's checksum
607 // algorithm. Appending the subject string then simulates LibXDiff.
608 return strrev( hash( 'adler32', $init . $s, true ) );
611 function uncompress() {
612 if ( !$this->mDiffs
) {
616 $mDiffsCount = count( $this->mDiffs
);
617 for ( $diffKey = 0; $diffKey < $mDiffsCount; $diffKey++
) {
618 $textKey = $this->mDiffMap
[$diffKey];
619 $text = $this->patch( $tail, $this->mDiffs
[$diffKey] );
620 $this->mItems
[$textKey] = $text;
630 if ( !count( $this->mItems
) ) {
634 // Take forward differences to improve the compression ratio for sequences
637 foreach ( $this->mDiffMap
as $i ) {
645 'diffs' => $this->mDiffs
,
649 if ( isset( $this->mDefaultKey
) ) {
650 $info['default'] = $this->mDefaultKey
;
652 $this->mCompressed
= gzdeflate( serialize( $info ) );
653 return [ 'mCompressed' ];
656 function __wakeup() {
657 // addItem() doesn't work if mItems is partially filled from mDiffs
658 $this->mFrozen
= true;
659 $info = unserialize( gzinflate( $this->mCompressed
) );
660 unset( $this->mCompressed
);
667 if ( isset( $info['default'] ) ) {
668 $this->mDefaultKey
= $info['default'];
670 $this->mDiffs
= $info['diffs'];
671 if ( isset( $info['base'] ) ) {
673 $this->mDiffMap
= range( 0, count( $this->mDiffs
) - 1 );
674 array_unshift( $this->mDiffs
,
675 pack( 'VVCV', 0, 0, self
::XDL_BDOP_INSB
, strlen( $info['base'] ) ) .
679 $map = explode( ',', $info['map'] );
681 $this->mDiffMap
= [];
682 foreach ( $map as $i ) {
684 $this->mDiffMap
[] = $cur;
691 * Helper function for compression jobs
692 * Returns true until the object is "full" and ready to be committed
697 return $this->mSize
< $this->mMaxSize
698 && count( $this->mItems
) < $this->mMaxCount
;