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;
82 public function __construct() {
83 if ( !function_exists( 'gzdeflate' ) ) {
84 throw new MWException( "Need zlib support to read or write this "
85 . "kind of history object (ConcatenatedGzipHistoryBlob)\n" );
93 public function addItem( $text ) {
96 if ( !isset( $this->mItems
[$hash] ) ) {
97 $this->mItems
[$hash] = $text;
98 $this->mSize +
= strlen( $text );
104 * @param string $hash
107 public function getItem( $hash ) {
109 if ( array_key_exists( $hash, $this->mItems
) ) {
110 return $this->mItems
[$hash];
117 * @param string $text
120 public function setText( $text ) {
122 $this->mDefaultHash
= $this->addItem( $text );
128 public function getText() {
130 return $this->getItem( $this->mDefaultHash
);
136 * @param string $hash
138 public function removeItem( $hash ) {
139 $this->mSize
-= strlen( $this->mItems
[$hash] );
140 unset( $this->mItems
[$hash] );
144 * Compress the bulk data in the object
146 public function compress() {
147 if ( !$this->mCompressed
) {
148 $this->mItems
= gzdeflate( serialize( $this->mItems
) );
149 $this->mCompressed
= true;
154 * Uncompress bulk data
156 public function uncompress() {
157 if ( $this->mCompressed
) {
158 $this->mItems
= unserialize( gzinflate( $this->mItems
) );
159 $this->mCompressed
= false;
168 return [ 'mVersion', 'mCompressed', 'mItems', 'mDefaultHash' ];
171 function __wakeup() {
176 * Helper function for compression jobs
177 * Returns true until the object is "full" and ready to be committed
181 public function isHappy() {
182 return $this->mSize
< $this->mMaxSize
183 && count( $this->mItems
) < $this->mMaxCount
;
188 * Pointer object for an item within a CGZ blob stored in the text table.
190 class HistoryBlobStub
{
192 * @var array One-step cache variable to hold base blobs; operations that
193 * pull multiple revisions may often pull multiple times from the same
194 * blob. By keeping the last-used one open, we avoid redundant
195 * unserialization and decompression overhead.
197 protected static $blobCache = [];
209 * @param string $hash The content hash of the text
210 * @param int $oldid The old_id for the CGZ object
212 function __construct( $hash = '', $oldid = 0 ) {
213 $this->mHash
= $hash;
217 * Sets the location (old_id) of the main object to which this object
221 function setLocation( $id ) {
226 * Sets the location (old_id) of the referring object
229 function setReferrer( $id ) {
234 * Gets the location of the referring object
237 function getReferrer() {
245 if ( isset( self
::$blobCache[$this->mOldId
] ) ) {
246 $obj = self
::$blobCache[$this->mOldId
];
248 $dbr = wfGetDB( DB_SLAVE
);
249 $row = $dbr->selectRow(
251 [ 'old_flags', 'old_text' ],
252 [ 'old_id' => $this->mOldId
]
259 $flags = explode( ',', $row->old_flags
);
260 if ( in_array( 'external', $flags ) ) {
261 $url = $row->old_text
;
262 $parts = explode( '://', $url, 2 );
263 if ( !isset( $parts[1] ) ||
$parts[1] == '' ) {
266 $row->old_text
= ExternalStore
::fetchFromURL( $url );
270 if ( !in_array( 'object', $flags ) ) {
274 if ( in_array( 'gzip', $flags ) ) {
275 // This shouldn't happen, but a bug in the compress script
276 // may at times gzip-compress a HistoryBlob object row.
277 $obj = unserialize( gzinflate( $row->old_text
) );
279 $obj = unserialize( $row->old_text
);
282 if ( !is_object( $obj ) ) {
283 // Correct for old double-serialization bug.
284 $obj = unserialize( $obj );
287 // Save this item for reference; if pulling many
288 // items in a row we'll likely use it again.
290 self
::$blobCache = [ $this->mOldId
=> $obj ];
293 return $obj->getItem( $this->mHash
);
297 * Get the content hash
307 * To speed up conversion from 1.4 to 1.5 schema, text rows can refer to the
308 * leftover cur table as the backend. This avoids expensively copying hundreds
309 * of megabytes of data during the conversion downtime.
311 * Serialized HistoryBlobCurStub objects will be inserted into the text table
312 * on conversion if $wgLegacySchemaConversion is set to true.
314 class HistoryBlobCurStub
{
319 * @param int $curid The cur_id pointed to
321 function __construct( $curid = 0 ) {
322 $this->mCurId
= $curid;
326 * Sets the location (cur_id) of the main object to which this object
331 function setLocation( $id ) {
336 * @return string|bool
339 $dbr = wfGetDB( DB_SLAVE
);
340 $row = $dbr->selectRow( 'cur', [ 'cur_text' ], [ 'cur_id' => $this->mCurId
] );
344 return $row->cur_text
;
349 * Diff-based history compression
350 * Requires xdiff 1.5+ and zlib
352 class DiffHistoryBlob
implements HistoryBlob
{
353 /** @var array Uncompressed item cache */
356 /** @var int Total uncompressed size */
360 * @var array Array of diffs. If a diff D from A to B is notated D = B - A,
361 * and Z is an empty string:
363 * { item[map[i]] - item[map[i-1]] where i > 0
365 * { item[map[i]] - Z where i = 0
369 /** @var array The diff map, see above */
372 /** @var int The key for getText()
376 /** @var string Compressed storage */
379 /** @var bool True if the object is locked against further writes */
380 public $mFrozen = false;
383 * @var int The maximum uncompressed size before the object becomes sad
384 * Should be less than max_allowed_packet
386 public $mMaxSize = 10000000;
388 /** @var int The maximum number of text items before the object becomes sad */
389 public $mMaxCount = 100;
391 /** Constants from xdiff.h */
392 const XDL_BDOP_INS
= 1;
393 const XDL_BDOP_CPY
= 2;
394 const XDL_BDOP_INSB
= 3;
396 function __construct() {
397 if ( !function_exists( 'gzdeflate' ) ) {
398 throw new MWException( "Need zlib support to read or write DiffHistoryBlob\n" );
403 * @throws MWException
404 * @param string $text
407 function addItem( $text ) {
408 if ( $this->mFrozen
) {
409 throw new MWException( __METHOD__
. ": Cannot add more items after sleep/wakeup" );
412 $this->mItems
[] = $text;
413 $this->mSize +
= strlen( $text );
414 $this->mDiffs
= null; // later
415 return count( $this->mItems
) - 1;
422 function getItem( $key ) {
423 return $this->mItems
[$key];
427 * @param string $text
429 function setText( $text ) {
430 $this->mDefaultKey
= $this->addItem( $text );
437 return $this->getItem( $this->mDefaultKey
);
441 * @throws MWException
443 function compress() {
444 if ( !function_exists( 'xdiff_string_rabdiff' ) ) {
445 throw new MWException( "Need xdiff 1.5+ support to write DiffHistoryBlob\n" );
447 if ( isset( $this->mDiffs
) ) {
448 // Already compressed
451 if ( !count( $this->mItems
) ) {
456 // Create two diff sequences: one for main text and one for small text
471 $mItemsCount = count( $this->mItems
);
472 for ( $i = 0; $i < $mItemsCount; $i++
) {
473 $text = $this->mItems
[$i];
477 $mainTail = $sequences['main']['tail'];
478 if ( strlen( $text ) < strlen( $mainTail ) * $smallFactor ) {
484 $seq =& $sequences[$seqName];
485 $tail = $seq['tail'];
486 $diff = $this->diff( $tail, $text );
487 $seq['diffs'][] = $diff;
489 $seq['tail'] = $text;
491 unset( $seq ); // unlink dangerous alias
493 // Knit the sequences together
496 $this->mDiffMap
= [];
497 foreach ( $sequences as $seq ) {
498 if ( !count( $seq['diffs'] ) ) {
501 if ( $tail === '' ) {
502 $this->mDiffs
[] = $seq['diffs'][0];
504 $head = $this->patch( '', $seq['diffs'][0] );
505 $this->mDiffs
[] = $this->diff( $tail, $head );
507 $this->mDiffMap
[] = $seq['map'][0];
508 $diffsCount = count( $seq['diffs'] );
509 for ( $i = 1; $i < $diffsCount; $i++
) {
510 $this->mDiffs
[] = $seq['diffs'][$i];
511 $this->mDiffMap
[] = $seq['map'][$i];
513 $tail = $seq['tail'];
522 function diff( $t1, $t2 ) {
523 # Need to do a null concatenation with warnings off, due to bugs in the current version of xdiff
524 # "String is not zero-terminated"
525 MediaWiki\
suppressWarnings();
526 $diff = xdiff_string_rabdiff( $t1, $t2 ) . '';
527 MediaWiki\restoreWarnings
();
532 * @param string $base
533 * @param string $diff
534 * @return bool|string
536 function patch( $base, $diff ) {
537 if ( function_exists( 'xdiff_string_bpatch' ) ) {
538 MediaWiki\
suppressWarnings();
539 $text = xdiff_string_bpatch( $base, $diff ) . '';
540 MediaWiki\restoreWarnings
();
544 # Pure PHP implementation
546 $header = unpack( 'Vofp/Vcsize', substr( $diff, 0, 8 ) );
548 # Check the checksum if hash extension is available
549 $ofp = $this->xdiffAdler32( $base );
550 if ( $ofp !== false && $ofp !== substr( $diff, 0, 4 ) ) {
551 wfDebug( __METHOD__
. ": incorrect base checksum\n" );
554 if ( $header['csize'] != strlen( $base ) ) {
555 wfDebug( __METHOD__
. ": incorrect base length\n" );
561 while ( $p < strlen( $diff ) ) {
562 $x = unpack( 'Cop', substr( $diff, $p, 1 ) );
566 case self
::XDL_BDOP_INS
:
567 $x = unpack( 'Csize', substr( $diff, $p, 1 ) );
569 $out .= substr( $diff, $p, $x['size'] );
572 case self
::XDL_BDOP_INSB
:
573 $x = unpack( 'Vcsize', substr( $diff, $p, 4 ) );
575 $out .= substr( $diff, $p, $x['csize'] );
578 case self
::XDL_BDOP_CPY
:
579 $x = unpack( 'Voff/Vcsize', substr( $diff, $p, 8 ) );
581 $out .= substr( $base, $x['off'], $x['csize'] );
584 wfDebug( __METHOD__
. ": invalid op\n" );
592 * Compute a binary "Adler-32" checksum as defined by LibXDiff, i.e. with
593 * the bytes backwards and initialised with 0 instead of 1. See bug 34428.
596 * @return string|bool False if the hash extension is not available
598 function xdiffAdler32( $s ) {
599 if ( !function_exists( 'hash' ) ) {
604 if ( $init === null ) {
605 $init = str_repeat( "\xf0", 205 ) . "\xee" . str_repeat( "\xf0", 67 ) . "\x02";
608 // The real Adler-32 checksum of $init is zero, so it initialises the
609 // state to zero, as it is at the start of LibXDiff's checksum
610 // algorithm. Appending the subject string then simulates LibXDiff.
611 return strrev( hash( 'adler32', $init . $s, true ) );
614 function uncompress() {
615 if ( !$this->mDiffs
) {
619 $mDiffsCount = count( $this->mDiffs
);
620 for ( $diffKey = 0; $diffKey < $mDiffsCount; $diffKey++
) {
621 $textKey = $this->mDiffMap
[$diffKey];
622 $text = $this->patch( $tail, $this->mDiffs
[$diffKey] );
623 $this->mItems
[$textKey] = $text;
633 if ( !count( $this->mItems
) ) {
637 // Take forward differences to improve the compression ratio for sequences
640 foreach ( $this->mDiffMap
as $i ) {
648 'diffs' => $this->mDiffs
,
652 if ( isset( $this->mDefaultKey
) ) {
653 $info['default'] = $this->mDefaultKey
;
655 $this->mCompressed
= gzdeflate( serialize( $info ) );
656 return [ 'mCompressed' ];
659 function __wakeup() {
660 // addItem() doesn't work if mItems is partially filled from mDiffs
661 $this->mFrozen
= true;
662 $info = unserialize( gzinflate( $this->mCompressed
) );
663 unset( $this->mCompressed
);
670 if ( isset( $info['default'] ) ) {
671 $this->mDefaultKey
= $info['default'];
673 $this->mDiffs
= $info['diffs'];
674 if ( isset( $info['base'] ) ) {
676 $this->mDiffMap
= range( 0, count( $this->mDiffs
) - 1 );
677 array_unshift( $this->mDiffs
,
678 pack( 'VVCV', 0, 0, self
::XDL_BDOP_INSB
, strlen( $info['base'] ) ) .
682 $map = explode( ',', $info['map'] );
684 $this->mDiffMap
= [];
685 foreach ( $map as $i ) {
687 $this->mDiffMap
[] = $cur;
694 * Helper function for compression jobs
695 * Returns true until the object is "full" and ready to be committed
700 return $this->mSize
< $this->mMaxSize
701 && count( $this->mItems
) < $this->mMaxCount
;