MediaWiki  master
MediumSpecificBagOStuff.php
Go to the documentation of this file.
1 <?php
24 use Wikimedia\WaitConditionLoop;
25 
34 abstract class MediumSpecificBagOStuff extends BagOStuff {
36  protected $locks = [];
38  protected $syncTimeout;
40  protected $segmentationSize;
43 
45  private $duplicateKeyLookups = [];
47  private $reportDupes = false;
49  private $dupeTrackScheduled = false;
50 
52  protected $preparedValues = [];
53 
55  private const SEGMENT_COMPONENT = 'segment';
56 
58  protected const PASS_BY_REF = -1;
59 
60  protected const METRIC_OP_GET = 'get';
61  protected const METRIC_OP_SET = 'set';
62  protected const METRIC_OP_DELETE = 'delete';
63  protected const METRIC_OP_CHANGE_TTL = 'change_ttl';
64  protected const METRIC_OP_ADD = 'add';
65  protected const METRIC_OP_INCR = 'incr';
66  protected const METRIC_OP_DECR = 'decr';
67  protected const METRIC_OP_CAS = 'cas';
68 
69  protected const LOCK_RCLASS = 0;
70  protected const LOCK_DEPTH = 1;
71  protected const LOCK_TIME = 2;
72  protected const LOCK_EXPIRY = 3;
73 
91  public function __construct( array $params = [] ) {
92  parent::__construct( $params );
93 
94  if ( !empty( $params['reportDupes'] ) && $this->asyncHandler ) {
95  $this->reportDupes = true;
96  }
97 
98  $this->syncTimeout = $params['syncTimeout'] ?? 3;
99  $this->segmentationSize = $params['segmentationSize'] ?? 8388608; // 8MiB
100  $this->segmentedValueMaxSize = $params['segmentedValueMaxSize'] ?? 67108864; // 64MiB
101  }
102 
116  public function get( $key, $flags = 0 ) {
117  $this->trackDuplicateKeys( $key );
118 
119  return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
120  }
121 
126  private function trackDuplicateKeys( $key ) {
127  if ( !$this->reportDupes ) {
128  return;
129  }
130 
131  if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
132  // Track that we have seen this key. This N-1 counting style allows
133  // easy filtering with array_filter() later.
134  $this->duplicateKeyLookups[$key] = 0;
135  } else {
136  $this->duplicateKeyLookups[$key] += 1;
137 
138  if ( $this->dupeTrackScheduled === false ) {
139  $this->dupeTrackScheduled = true;
140  // Schedule a callback that logs keys processed more than once by get().
141  call_user_func( $this->asyncHandler, function () {
142  $dups = array_filter( $this->duplicateKeyLookups );
143  foreach ( $dups as $key => $count ) {
144  $this->logger->warning(
145  'Duplicate get(): "{key}" fetched {count} times',
146  // Count is N-1 of the actual lookup count
147  [ 'key' => $key, 'count' => $count + 1, ]
148  );
149  }
150  } );
151  }
152  }
153  }
154 
165  abstract protected function doGet( $key, $flags = 0, &$casToken = null );
166 
176  public function set( $key, $value, $exptime = 0, $flags = 0 ) {
177  list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
178  // Only when all segments (if any) are stored should the main key be changed
179  return $usable ? $this->doSet( $key, $entry, $exptime, $flags ) : false;
180  }
181 
191  abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
192 
204  public function delete( $key, $flags = 0 ) {
205  if ( !$this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
206  return $this->doDelete( $key, $flags );
207  }
208 
209  $mainValue = $this->doGet( $key, self::READ_LATEST );
210  if ( !$this->doDelete( $key, $flags ) ) {
211  return false;
212  }
213 
214  if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
215  return true; // no segments to delete
216  }
217 
218  $orderedKeys = array_map(
219  function ( $segmentHash ) use ( $key ) {
220  return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
221  },
223  );
224 
225  return $this->deleteMulti( $orderedKeys, $flags & ~self::WRITE_PRUNE_SEGMENTS );
226  }
227 
235  abstract protected function doDelete( $key, $flags = 0 );
236 
237  public function add( $key, $value, $exptime = 0, $flags = 0 ) {
238  list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
239  // Only when all segments (if any) are stored should the main key be changed
240  return $usable ? $this->doAdd( $key, $entry, $exptime, $flags ) : false;
241  }
242 
252  abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
253 
270  public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
271  return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
272  }
273 
283  final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
284  $attemptsLeft = $attempts;
285  do {
286  $token = self::PASS_BY_REF; // passed by reference
287  // Get the old value and CAS token from cache
288  $watchPoint = $this->watchErrors();
289  $currentValue = $this->resolveSegments(
290  $key,
291  $this->doGet( $key, $flags, $token )
292  );
293  if ( $this->getLastError( $watchPoint ) ) {
294  // Don't spam slow retries due to network problems (retry only on races)
295  $this->logger->warning(
296  __METHOD__ . ' failed due to read I/O error on get() for {key}.',
297  [ 'key' => $key ]
298  );
299  $success = false;
300  break;
301  }
302 
303  // Derive the new value from the old value
304  $value = $callback( $this, $key, $currentValue, $exptime );
305  $keyWasNonexistant = ( $currentValue === false );
306  $valueMatchesOldValue = ( $value === $currentValue );
307  unset( $currentValue ); // free RAM in case the value is large
308 
309  $watchPoint = $this->watchErrors();
310  if ( $value === false || $exptime < 0 ) {
311  $success = true; // do nothing
312  } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
313  $success = true; // recently set by another thread to the same value
314  } elseif ( $keyWasNonexistant ) {
315  // Try to create the key, failing if it gets created in the meantime
316  $success = $this->add( $key, $value, $exptime, $flags );
317  } else {
318  // Try to update the key, failing if it gets changed in the meantime
319  $success = $this->cas( $token, $key, $value, $exptime, $flags );
320  }
321  if ( $this->getLastError( $watchPoint ) ) {
322  // Don't spam slow retries due to network problems (retry only on races)
323  $this->logger->warning(
324  __METHOD__ . ' failed due to write I/O error for {key}.',
325  [ 'key' => $key ]
326  );
327  $success = false;
328  break;
329  }
330 
331  } while ( !$success && --$attemptsLeft );
332 
333  return $success;
334  }
335 
346  protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
347  if ( $casToken === null ) {
348  $this->logger->warning(
349  __METHOD__ . ' got empty CAS token for {key}.',
350  [ 'key' => $key ]
351  );
352 
353  return false; // caller may have meant to use add()?
354  }
355 
356  list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
357  // Only when all segments (if any) are stored should the main key be changed
358  return $usable ? $this->doCas( $casToken, $key, $entry, $exptime, $flags ) : false;
359  }
360 
371  protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
372  // @TODO: the use of lock() assumes that all other relevant sets() use a lock
373  if ( !$this->lock( $key, 0 ) ) {
374  return false; // non-blocking
375  }
376 
377  $curCasToken = self::PASS_BY_REF; // passed by reference
378  $watchPoint = $this->watchErrors();
379  $exists = ( $this->doGet( $key, self::READ_LATEST, $curCasToken ) !== false );
380  if ( $this->getLastError( $watchPoint ) ) {
381  // Fail if the old CAS token could not be read
382  $success = false;
383  $this->logger->warning(
384  __METHOD__ . ' failed due to write I/O error for {key}.',
385  [ 'key' => $key ]
386  );
387  } elseif ( $exists && $this->tokensMatch( $casToken, $curCasToken ) ) {
388  $success = $this->doSet( $key, $value, $exptime, $flags );
389  } else {
390  $success = false; // mismatched or failed
391  $this->logger->info(
392  __METHOD__ . ' failed due to race condition for {key}.',
393  [ 'key' => $key, 'key_exists' => $exists ]
394  );
395  }
396 
397  $this->unlock( $key );
398 
399  return $success;
400  }
401 
407  final protected function tokensMatch( $value, $otherValue ) {
408  $type = gettype( $value );
409  // Ideally, tokens are counters, timestamps, hashes, or serialized PHP values.
410  // However, some classes might use the PHP values themselves.
411  if ( $type !== gettype( $otherValue ) ) {
412  return false;
413  }
414  // Serialize both tokens to strictly compare objects or arrays (which might objects
415  // nested inside). Note that this will not apply if integer/string CAS tokens are used.
416  if ( $type === 'array' || $type === 'object' ) {
417  return ( serialize( $value ) === serialize( $otherValue ) );
418  }
419  // For string/integer tokens, use a simple comparison
420  return ( $value === $otherValue );
421  }
422 
440  public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
441  return $this->doChangeTTL( $key, $exptime, $flags );
442  }
443 
450  protected function doChangeTTL( $key, $exptime, $flags ) {
451  // @TODO: the use of lock() assumes that all other relevant sets() use a lock
452  if ( !$this->lock( $key, 0 ) ) {
453  return false;
454  }
455 
456  $expiry = $this->getExpirationAsTimestamp( $exptime );
457  $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
458 
459  // Use doGet() to avoid having to trigger resolveSegments()
460  $blob = $this->doGet( $key, self::READ_LATEST );
461  if ( $blob ) {
462  if ( $delete ) {
463  $ok = $this->doDelete( $key, $flags );
464  } else {
465  $ok = $this->doSet( $key, $blob, $exptime, $flags );
466  }
467  } else {
468  $ok = false;
469  }
470 
471  $this->unlock( $key );
472 
473  return $ok;
474  }
475 
476  public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 ) {
477  $step = (int)$step;
478  $init = is_int( $init ) ? $init : $step;
479 
480  return $this->doIncrWithInit( $key, $exptime, $step, $init, $flags );
481  }
482 
491  abstract protected function doIncrWithInit( $key, $exptime, $step, $init, $flags );
492 
500  public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' ) {
501  $exptime = min( $exptime ?: INF, self::TTL_DAY );
502 
503  $acquired = false;
504 
505  if ( isset( $this->locks[$key] ) ) {
506  // Already locked; avoid deadlocks and allow lock reentry if specified
507  if ( $rclass != '' && $this->locks[$key][self::LOCK_RCLASS] === $rclass ) {
508  ++$this->locks[$key][self::LOCK_DEPTH];
509  $acquired = true;
510  }
511  } else {
512  // Not already locked; acquire a lock on the backend
513  $lockTsUnix = $this->doLock( $key, $timeout, $exptime );
514  if ( $lockTsUnix !== null ) {
515  $this->locks[$key] = [
516  self::LOCK_RCLASS => $rclass,
517  self::LOCK_DEPTH => 1,
518  self::LOCK_TIME => $lockTsUnix,
519  self::LOCK_EXPIRY => $lockTsUnix + $exptime
520  ];
521  $acquired = true;
522  }
523  }
524 
525  return $acquired;
526  }
527 
536  protected function doLock( $key, $timeout, $exptime ) {
537  $lockTsUnix = null;
538 
539  $fname = __METHOD__;
540  $loop = new WaitConditionLoop(
541  function () use ( $key, $exptime, $fname, &$lockTsUnix ) {
542  $watchPoint = $this->watchErrors();
543  if ( $this->add( $this->makeLockKey( $key ), 1, $exptime ) ) {
544  $lockTsUnix = microtime( true );
545 
546  return WaitConditionLoop::CONDITION_REACHED; // locked!
547  } elseif ( $this->getLastError( $watchPoint ) ) {
548  $this->logger->warning(
549  "$fname failed due to I/O error for {key}.",
550  [ 'key' => $key ]
551  );
552 
553  return WaitConditionLoop::CONDITION_ABORTED; // network partition?
554  }
555 
556  return WaitConditionLoop::CONDITION_CONTINUE;
557  },
558  $timeout
559  );
560  $code = $loop->invoke();
561 
562  if ( $code === $loop::CONDITION_TIMED_OUT ) {
563  $this->logger->warning(
564  "$fname failed due to timeout for {key}.",
565  [ 'key' => $key, 'timeout' => $timeout ]
566  );
567  }
568 
569  return $lockTsUnix;
570  }
571 
578  public function unlock( $key ) {
579  $released = false;
580 
581  if ( isset( $this->locks[$key] ) ) {
582  if ( --$this->locks[$key][self::LOCK_DEPTH] > 0 ) {
583  $released = true;
584  } else {
585  $released = $this->doUnlock( $key );
586  unset( $this->locks[$key] );
587  if ( !$released ) {
588  $this->logger->warning(
589  __METHOD__ . ' failed to release lock for {key}.',
590  [ 'key' => $key ]
591  );
592  }
593  }
594  } else {
595  $this->logger->warning(
596  __METHOD__ . ' no lock to release for {key}.',
597  [ 'key' => $key ]
598  );
599  }
600 
601  return $released;
602  }
603 
610  protected function doUnlock( $key ) {
611  // Estimate the remaining TTL of the lock key
612  $curTTL = $this->locks[$key][self::LOCK_EXPIRY] - $this->getCurrentTime();
613  // Maximum expected one-way-delay for a query to reach the backend
614  $maxOWD = 0.050;
615 
616  $released = false;
617 
618  if ( ( $curTTL - $maxOWD ) > 0 ) {
619  // The lock key is extremely unlikely to expire before a deletion operation
620  // sent from this method arrives on the relevant backend server
621  $released = $this->doDelete( $this->makeLockKey( $key ) );
622  } else {
623  // It is unsafe for this method to delete the lock key due to the risk of it
624  // expiring and being claimed by another thread before the deletion operation
625  // arrives on the backend server
626  $this->logger->warning(
627  "Lock for {key} held too long ({age} sec).",
628  [ 'key' => $key, 'curTTL' => $curTTL ]
629  );
630  }
631 
632  return $released;
633  }
634 
639  protected function makeLockKey( $key ) {
640  return "$key:lock";
641  }
642 
644  $timestamp,
645  callable $progress = null,
646  $limit = INF,
647  string $tag = null
648  ) {
649  return false;
650  }
651 
658  public function getMulti( array $keys, $flags = 0 ) {
659  $foundByKey = $this->doGetMulti( $keys, $flags );
660 
661  $res = [];
662  foreach ( $keys as $key ) {
663  // Resolve one blob at a time (avoids too much I/O at once)
664  if ( array_key_exists( $key, $foundByKey ) ) {
665  // A value should not appear in the key if a segment is missing
666  $value = $this->resolveSegments( $key, $foundByKey[$key] );
667  if ( $value !== false ) {
668  $res[$key] = $value;
669  }
670  }
671  }
672 
673  return $res;
674  }
675 
682  protected function doGetMulti( array $keys, $flags = 0 ) {
683  $res = [];
684  foreach ( $keys as $key ) {
685  $val = $this->doGet( $key, $flags );
686  if ( $val !== false ) {
687  $res[$key] = $val;
688  }
689  }
690 
691  return $res;
692  }
693 
705  public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) {
706  if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
707  throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
708  }
709 
710  return $this->doSetMulti( $valueByKey, $exptime, $flags );
711  }
712 
719  protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
720  $res = true;
721  foreach ( $data as $key => $value ) {
722  $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
723  }
724 
725  return $res;
726  }
727 
738  public function deleteMulti( array $keys, $flags = 0 ) {
739  if ( $this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
740  throw new InvalidArgumentException( __METHOD__ . ' got WRITE_PRUNE_SEGMENTS' );
741  }
742 
743  return $this->doDeleteMulti( $keys, $flags );
744  }
745 
751  protected function doDeleteMulti( array $keys, $flags = 0 ) {
752  $res = true;
753  foreach ( $keys as $key ) {
754  $res = $this->doDelete( $key, $flags ) && $res;
755  }
756  return $res;
757  }
758 
769  public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
770  return $this->doChangeTTLMulti( $keys, $exptime, $flags );
771  }
772 
779  protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
780  $res = true;
781  foreach ( $keys as $key ) {
782  $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
783  }
784 
785  return $res;
786  }
787 
795  final protected function resolveSegments( $key, $mainValue ) {
796  if ( SerializedValueContainer::isUnified( $mainValue ) ) {
797  return $this->unserialize( $mainValue->{SerializedValueContainer::UNIFIED_DATA} );
798  }
799 
800  if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
801  $orderedKeys = array_map(
802  function ( $segmentHash ) use ( $key ) {
803  return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
804  },
806  );
807 
808  $segmentsByKey = $this->doGetMulti( $orderedKeys );
809 
810  $parts = [];
811  foreach ( $orderedKeys as $segmentKey ) {
812  if ( isset( $segmentsByKey[$segmentKey] ) ) {
813  $parts[] = $segmentsByKey[$segmentKey];
814  } else {
815  return false; // missing segment
816  }
817  }
818 
819  return $this->unserialize( implode( '', $parts ) );
820  }
821 
822  return $mainValue;
823  }
824 
825  final public function addBusyCallback( callable $workCallback ) {
826  wfDeprecated( __METHOD__, '1.39' );
827  }
828 
839  final protected function makeValueOrSegmentList( $key, $value, $exptime, $flags ) {
840  $entry = $value;
841  $usable = true;
842 
843  if (
844  $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) &&
845  !is_int( $value ) && // avoid breaking incr()/decr()
846  is_finite( $this->segmentationSize )
847  ) {
848  $segmentSize = $this->segmentationSize;
849  $maxTotalSize = $this->segmentedValueMaxSize;
850 
851  $serialized = $this->getSerialized( $value, $key );
852  $size = strlen( $serialized );
853  if ( $size > $maxTotalSize ) {
854  $this->logger->warning(
855  "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
856  [ 'key' => $key ]
857  );
858  } elseif ( $size <= $segmentSize ) {
859  // The serialized value was already computed, so just use it inline
861  } else {
862  // Split the serialized value into chunks and store them at different keys
863  $chunksByKey = [];
864  $segmentHashes = [];
865  $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
866  for ( $i = 0; $i < $count; ++$i ) {
867  $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
868  $hash = sha1( $segment );
869  $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
870  $chunksByKey[$chunkKey] = $segment;
871  $segmentHashes[] = $hash;
872  }
873  $flags &= ~self::WRITE_ALLOW_SEGMENTS;
874  $usable = $this->setMulti( $chunksByKey, $exptime, $flags );
875  $entry = SerializedValueContainer::newSegmented( $segmentHashes );
876  }
877  }
878 
879  return [ $entry, $usable ];
880  }
881 
887  final protected function isRelativeExpiration( $exptime ) {
888  return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
889  }
890 
904  final protected function getExpirationAsTimestamp( $exptime ) {
905  if ( $exptime == self::TTL_INDEFINITE ) {
906  return $exptime;
907  }
908 
909  return $this->isRelativeExpiration( $exptime )
910  ? intval( $this->getCurrentTime() + $exptime )
911  : $exptime;
912  }
913 
928  final protected function getExpirationAsTTL( $exptime ) {
929  if ( $exptime == self::TTL_INDEFINITE ) {
930  return $exptime;
931  }
932 
933  return $this->isRelativeExpiration( $exptime )
934  ? $exptime
935  : (int)max( $exptime - $this->getCurrentTime(), 1 );
936  }
937 
944  final protected function isInteger( $value ) {
945  if ( is_int( $value ) ) {
946  return true;
947  } elseif ( !is_string( $value ) ) {
948  return false;
949  }
950 
951  $integer = (int)$value;
952 
953  return ( $value === (string)$integer );
954  }
955 
956  public function makeGlobalKey( $collection, ...$components ) {
957  return $this->makeKeyInternal( self::GLOBAL_KEYSPACE, func_get_args() );
958  }
959 
960  public function makeKey( $collection, ...$components ) {
961  return $this->makeKeyInternal( $this->keyspace, func_get_args() );
962  }
963 
964  protected function convertGenericKey( $key ) {
965  $components = $this->componentsFromGenericKey( $key );
966  if ( count( $components ) < 2 ) {
967  // Legacy key not from makeKey()/makeGlobalKey(); keep it as-is
968  return $key;
969  }
970 
971  $keyspace = array_shift( $components );
972 
973  return $this->makeKeyInternal( $keyspace, $components );
974  }
975 
976  public function getQoS( $flag ) {
977  return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
978  }
979 
980  public function getSegmentationSize() {
981  return $this->segmentationSize;
982  }
983 
984  public function getSegmentedValueMaxSize() {
985  return $this->segmentedValueMaxSize;
986  }
987 
988  public function setNewPreparedValues( array $valueByKey ) {
989  $this->preparedValues = [];
990 
991  $sizes = [];
992  foreach ( $valueByKey as $key => $value ) {
993  if ( $value === false ) {
994  $sizes[] = null; // not storable, don't bother
995  continue;
996  }
997 
998  $serialized = $this->serialize( $value );
999  $sizes[] = ( $serialized !== false ) ? strlen( $serialized ) : null;
1000 
1001  $this->preparedValues[$key] = [ $value, $serialized ];
1002  }
1003 
1004  return $sizes;
1005  }
1006 
1017  protected function getSerialized( $value, $key ) {
1018  // Reuse any available prepared (serialized) value
1019  if ( array_key_exists( $key, $this->preparedValues ) ) {
1020  list( $prepValue, $prepSerialized ) = $this->preparedValues[$key];
1021  // Normally, this comparison should only take a few microseconds to confirm a match.
1022  // Using "===" on variables of different types is always fast. It is also fast for
1023  // variables of matching type int, float, bool, null, and object. Lastly, it is fast
1024  // for comparing arrays/strings if they are copy-on-write references, which should be
1025  // the case at this point, assuming prepareValues() was called correctly.
1026  if ( $prepValue === $value ) {
1027  unset( $this->preparedValues[$key] );
1028 
1029  return $prepSerialized;
1030  }
1031  }
1032 
1033  $this->checkValueSerializability( $value, $key );
1034 
1035  return $this->serialize( $value );
1036  }
1037 
1047  protected function guessSerialValueSize( $value, $depth = 0, &$loops = 0 ) {
1048  if ( is_string( $value ) ) {
1049  // E.g. "<type><delim1><quote><value><quote><delim2>"
1050  return strlen( $value ) + 5;
1051  } else {
1052  return strlen( serialize( $value ) );
1053  }
1054  }
1055 
1063  protected function guessSerialSizeOfValues( array $values ) {
1064  $sizes = [];
1065  foreach ( $values as $value ) {
1066  $sizes[] = $this->guessSerialValueSize( $value );
1067  }
1068 
1069  return $sizes;
1070  }
1071 
1092  private function checkValueSerializability( $value, $key ) {
1093  if ( is_array( $value ) ) {
1094  $this->checkIterableMapSerializability( $value, $key );
1095  } elseif ( is_object( $value ) ) {
1096  // Note that Closure instances count as objects
1097  if ( $value instanceof stdClass ) {
1098  $this->checkIterableMapSerializability( $value, $key );
1099  } elseif ( !( $value instanceof JsonSerializable ) ) {
1100  $this->logger->warning(
1101  "{class} value for '{cachekey}'; serialization is suspect.",
1102  [ 'cachekey' => $key, 'class' => get_class( $value ) ]
1103  );
1104  }
1105  }
1106  }
1107 
1112  private function checkIterableMapSerializability( $value, $key ) {
1113  foreach ( $value as $index => $entry ) {
1114  if ( is_object( $entry ) ) {
1115  // Note that Closure instances count as objects
1116  if (
1117  !( $entry instanceof stdClass ) &&
1118  !( $entry instanceof JsonSerializable )
1119  ) {
1120  $this->logger->warning(
1121  "{class} value for '{cachekey}' at '$index'; serialization is suspect.",
1122  [ 'cachekey' => $key, 'class' => get_class( $entry ) ]
1123  );
1124 
1125  return;
1126  }
1127  }
1128  }
1129  }
1130 
1136  protected function serialize( $value ) {
1137  return is_int( $value ) ? $value : serialize( $value );
1138  }
1139 
1145  protected function unserialize( $value ) {
1146  return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1147  }
1148 
1152  protected function debug( $text ) {
1153  $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] );
1154  }
1155 
1163  protected function updateOpStats( string $op, array $keyInfo ) {
1164  $deltasByMetric = [];
1165 
1166  foreach ( $keyInfo as $indexOrKey => $keyOrSizes ) {
1167  if ( is_array( $keyOrSizes ) ) {
1168  $key = $indexOrKey;
1169  list( $sPayloadSize, $rPayloadSize ) = $keyOrSizes;
1170  } else {
1171  $key = $keyOrSizes;
1172  $sPayloadSize = 0;
1173  $rPayloadSize = 0;
1174  }
1175 
1176  // Metric prefix for the cache wrapper and key collection name
1177  $prefix = $this->determineKeyPrefixForStats( $key );
1178 
1179  if ( $op === self::METRIC_OP_GET ) {
1180  // This operation was either a "hit" or "miss" for this key
1181  $name = "{$prefix}.{$op}_" . ( $rPayloadSize === false ? 'miss_rate' : 'hit_rate' );
1182  } else {
1183  // There is no concept of "hit" or "miss" for this operation
1184  $name = "{$prefix}.{$op}_call_rate";
1185  }
1186  $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + 1;
1187 
1188  if ( $sPayloadSize > 0 ) {
1189  $name = "{$prefix}.{$op}_bytes_sent";
1190  $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + $sPayloadSize;
1191  }
1192 
1193  if ( $rPayloadSize > 0 ) {
1194  $name = "{$prefix}.{$op}_bytes_read";
1195  $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + $rPayloadSize;
1196  }
1197  }
1198 
1199  foreach ( $deltasByMetric as $name => $delta ) {
1200  $this->stats->updateCount( $name, $delta );
1201  }
1202  }
1203 }
serialize()
unserialize( $serialized)
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
$success
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:87
fieldHasFlags( $field, $flags)
Definition: BagOStuff.php:613
Storage medium specific cache for storing items (e.g.
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
int $segmentationSize
Bytes; chunk size of segmented cache values.
cas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.
doDeleteMulti(array $keys, $flags=0)
setMulti(array $valueByKey, $exptime=0, $flags=0)
Batch insertion/replace.
guessSerialValueSize( $value, $depth=0, &$loops=0)
Estimate the size of a variable once serialized.
doChangeTTLMulti(array $keys, $exptime, $flags=0)
trackDuplicateKeys( $key)
Track the number of times that a given key has been used.
getExpirationAsTimestamp( $exptime)
Convert an optionally relative timestamp to an absolute time.
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
add( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
deleteMulti(array $keys, $flags=0)
Batch deletion.
checkValueSerializability( $value, $key)
Log if a new cache value does not appear suitable for serialization at a quick glance.
tokensMatch( $value, $otherValue)
addBusyCallback(callable $workCallback)
Let a callback be run to avoid wasting time on special blocking calls.
getSerialized( $value, $key)
Get the serialized form a value, using any applicable prepared value.
doSetMulti(array $data, $exptime=0, $flags=0)
doChangeTTL( $key, $exptime, $flags)
makeKey( $collection,... $components)
Make a cache key for the global keyspace and given components.
checkIterableMapSerializability( $value, $key)
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
unlock( $key)
Release an advisory lock on a key string.
doGetMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
doIncrWithInit( $key, $exptime, $step, $init, $flags)
updateOpStats(string $op, array $keyInfo)
array< string, array > $locks
Map of (key => (class, depth, expiry)
doCas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.
doDelete( $key, $flags=0)
Delete an item.
doLock( $key, $timeout, $exptime)
convertGenericKey( $key)
Convert a "generic" reversible cache key into one for this cache.
mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags)
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
getExpirationAsTTL( $exptime)
Convert an optionally absolute expiry time to a relative time.
resolveSegments( $key, $mainValue)
Get and reassemble the chunks of blob at the given key.
changeTTLMulti(array $keys, $exptime, $flags=0)
Change the expiration of multiple keys that exist.
changeTTL( $key, $exptime=0, $flags=0)
Change the expiration on a key if it exists.
incrWithInit( $key, $exptime, $step=1, $init=null, $flags=0)
Increase the value of the given key (no TTL change) if it exists or create it otherwise.
isInteger( $value)
Check if a value is an integer.
makeGlobalKey( $collection,... $components)
Make a cache key for the default keyspace and given components.
lock( $key, $timeout=6, $exptime=6, $rclass='')
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF, string $tag=null)
Delete all objects expiring before a certain date.
int $segmentedValueMaxSize
Bytes; maximum total size of a segmented cache value.
guessSerialSizeOfValues(array $values)
Estimate the size of a each variable once serialized.
makeValueOrSegmentList( $key, $value, $exptime, $flags)
Determine the entry (inline or segment list) to store under a key to save the value.
array[] $preparedValues
Map of (key => (PHP variable value, serialized value))
setNewPreparedValues(array $valueByKey)
Stage a set of new key values for storage and estimate the amount of bytes needed.
doGet( $key, $flags=0, &$casToken=null)
Get an item.
static newSegmented(array $segmentHashList)
foreach( $res as $row) $serialized