MediaWiki  master
BagOStuff.php
Go to the documentation of this file.
1 <?php
29 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
30 use Psr\Log\LoggerAwareInterface;
31 use Psr\Log\LoggerInterface;
32 use Psr\Log\NullLogger;
35 use Wikimedia\ScopedCallback;
36 
81 abstract class BagOStuff implements
85  LoggerAwareInterface
86 {
88  protected $stats;
90  protected $logger;
92  protected $asyncHandler;
97  protected $wrapperInfoByPrefix = [];
98 
100  protected $attrMap = [];
101 
103  protected $keyspace;
104 
109  protected $debugMode = true;
110 
113 
115  public const READ_LATEST = 1; // if supported, avoid reading stale data due to replication
116  public const READ_VERIFIED = 2; // promise that the caller handles detection of staleness
118  public const WRITE_SYNC = 4; // if supported, block until the write is fully replicated
119  public const WRITE_CACHE_ONLY = 8; // only change state of the in-memory cache
120  public const WRITE_ALLOW_SEGMENTS = 16; // allow partitioning of the value if it is large
121  public const WRITE_PRUNE_SEGMENTS = 32; // delete all the segments if the value is partitioned
122  public const WRITE_BACKGROUND = 64; // if supported, do not block on completion until the next read
123 
125  protected const GLOBAL_KEYSPACE = 'global';
127  protected const GLOBAL_PREFIX = 'global:';
129  protected const GLOBAL_PREFIX_LEN = 7;
130 
132  protected const ARG0_KEY = 0;
134  protected const ARG0_KEYARR = 1;
136  protected const ARG0_KEYMAP = 2;
138  protected const ARG0_NONKEY = 3;
139 
141  protected const RES_KEYMAP = 0;
143  protected const RES_NONKEY = 1;
144 
146  private const WRAPPER_STATS_GROUP = 0;
148  private const WRAPPER_COLLECTION_CALLBACK = 1;
149 
162  public function __construct( array $params = [] ) {
163  $this->keyspace = $params['keyspace'] ?? 'local';
164  $this->asyncHandler = $params['asyncHandler'] ?? null;
165  $this->stats = $params['stats'] ?? new NullStatsdDataFactory();
166  $this->setLogger( $params['logger'] ?? new NullLogger() );
167  }
168 
173  public function setLogger( LoggerInterface $logger ) {
174  $this->logger = $logger;
175  }
176 
181  public function getLogger() : LoggerInterface {
182  return $this->logger;
183  }
184 
189  public function setDebug( $enabled ) {
190  wfDeprecated( __METHOD__, '1.36' );
191  }
192 
206  final public function getWithSetCallback( $key, $exptime, $callback, $flags = 0 ) {
207  $value = $this->get( $key, $flags );
208 
209  if ( $value === false ) {
210  $value = $callback( $exptime );
211  if ( $value !== false && $exptime >= 0 ) {
212  $this->set( $key, $value, $exptime, $flags );
213  }
214  }
215 
216  return $value;
217  }
218 
232  abstract public function get( $key, $flags = 0 );
233 
243  abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
244 
256  abstract public function delete( $key, $flags = 0 );
257 
267  abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
268 
286  abstract public function merge(
287  $key,
288  callable $callback,
289  $exptime = 0,
290  $attempts = 10,
291  $flags = 0
292  );
293 
311  abstract public function changeTTL( $key, $exptime = 0, $flags = 0 );
312 
324  abstract public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' );
325 
332  abstract public function unlock( $key );
333 
350  final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
351  $expiry = min( $expiry ?: INF, self::TTL_DAY );
352 
353  if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
354  return null;
355  }
356 
357  $lSince = $this->getCurrentTime(); // lock timestamp
358 
359  return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
360  $latency = 0.050; // latency skew (err towards keeping lock present)
361  $age = ( $this->getCurrentTime() - $lSince + $latency );
362  if ( ( $age + $latency ) >= $expiry ) {
363  $this->logger->warning(
364  "Lock for {key} held too long ({age} sec).",
365  [ 'key' => $key, 'age' => $age ]
366  );
367  return; // expired; it's not "safe" to delete the key
368  }
369  $this->unlock( $key );
370  } );
371  }
372 
383  abstract public function deleteObjectsExpiringBefore(
384  $timestamp,
385  callable $progress = null,
386  $limit = INF
387  );
388 
396  abstract public function getMulti( array $keys, $flags = 0 );
397 
411  abstract public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 );
412 
425  abstract public function deleteMulti( array $keys, $flags = 0 );
426 
438  abstract public function changeTTLMulti( array $keys, $exptime, $flags = 0 );
439 
448  abstract public function incr( $key, $value = 1, $flags = 0 );
449 
458  abstract public function decr( $key, $value = 1, $flags = 0 );
459 
475  abstract public function incrWithInit( $key, $exptime, $value = 1, $init = null, $flags = 0 );
476 
482  abstract public function getLastError();
483 
488  abstract public function clearLastError();
489 
510  abstract public function addBusyCallback( callable $workCallback );
511 
525  abstract public function makeKeyInternal( $keyspace, $components );
526 
537  abstract public function makeGlobalKey( $collection, ...$components );
538 
549  abstract public function makeKey( $collection, ...$components );
550 
558  public function isKeyGlobal( $key ) {
559  return ( strncmp( $key, self::GLOBAL_PREFIX, self::GLOBAL_PREFIX_LEN ) === 0 );
560  }
561 
567  public function getQoS( $flag ) {
568  return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
569  }
570 
575  public function getSegmentationSize() {
576  return INF;
577  }
578 
583  public function getSegmentedValueMaxSize() {
584  return INF;
585  }
586 
593  final protected function fieldHasFlags( $field, $flags ) {
594  return ( ( $field & $flags ) === $flags );
595  }
596 
603  final protected function mergeFlagMaps( array $bags ) {
604  $map = [];
605  foreach ( $bags as $bag ) {
606  foreach ( $bag->attrMap as $attr => $rank ) {
607  if ( isset( $map[$attr] ) ) {
608  $map[$attr] = min( $map[$attr], $rank );
609  } else {
610  $map[$attr] = $rank;
611  }
612  }
613  }
614 
615  return $map;
616  }
617 
643  abstract public function setNewPreparedValues( array $valueByKey );
644 
668  string $prefixComponent,
669  string $statsGroup,
670  callable $collectionCallback
671  ) {
672  $this->wrapperInfoByPrefix[$prefixComponent] = [
673  self::WRAPPER_STATS_GROUP => $statsGroup,
674  self::WRAPPER_COLLECTION_CALLBACK => $collectionCallback
675  ];
676  }
677 
685  final protected function genericKeyFromComponents( ...$components ) {
686  if ( count( $components ) < 2 ) {
687  throw new InvalidArgumentException( "Missing keyspace or collection name" );
688  }
689 
690  $key = '';
691  foreach ( $components as $component ) {
692  if ( $key !== '' ) {
693  $key .= ':';
694  }
695  // Escape delimiter (":") and escape ("%") characters
696  $key .= strtr( $component, [ '%' => '%25', ':' => '%3A' ] );
697  }
698 
699  return $key;
700  }
701 
711  final protected function componentsFromGenericKey( $key ) {
712  // Note that the order of each corresponding search/replace pair matters
713  return str_replace( [ '%3A', '%25' ], [ ':', '%' ], explode( ':', $key ) );
714  }
715 
724  abstract protected function convertGenericKey( $key );
725 
735  protected function proxyCall( $method, $arg0Sig, $resSig, array $genericArgs ) {
736  // Get the corresponding store-specific cache keys...
737  $storeArgs = $genericArgs;
738  switch ( $arg0Sig ) {
739  case self::ARG0_KEY:
740  $storeArgs[0] = $this->convertGenericKey( $genericArgs[0] );
741  break;
742  case self::ARG0_KEYARR:
743  foreach ( $genericArgs[0] as $i => $genericKey ) {
744  $storeArgs[0][$i] = $this->convertGenericKey( $genericKey );
745  }
746  break;
747  case self::ARG0_KEYMAP:
748  $storeArgs[0] = [];
749  foreach ( $genericArgs[0] as $genericKey => $v ) {
750  $storeArgs[0][$this->convertGenericKey( $genericKey )] = $v;
751  }
752  break;
753  }
754 
755  // Result of invoking the method with the corresponding store-specific cache keys
756  $storeRes = $this->$method( ...$storeArgs );
757 
758  // Convert any store-specific cache keys in the result back to generic cache keys
759  if ( $resSig === self::RES_KEYMAP ) {
760  // Map of (store-specific cache key => generic cache key)
761  $genericKeyByStoreKey = array_combine( $storeArgs[0], $genericArgs[0] );
762 
763  $genericRes = [];
764  foreach ( $storeRes as $storeKey => $value ) {
765  $genericRes[$genericKeyByStoreKey[$storeKey]] = $value;
766  }
767  } else {
768  $genericRes = $storeRes;
769  }
770 
771  return $genericRes;
772  }
773 
778  protected function determineKeyPrefixForStats( $key ) {
779  $firstComponent = substr( $key, 0, strcspn( $key, ':' ) );
780 
781  $wrapperInfo = $this->wrapperInfoByPrefix[$firstComponent] ?? null;
782  if ( $wrapperInfo ) {
783  // Key has the prefix of a cache wrapper class that wraps BagOStuff
784  $collection = $wrapperInfo[self::WRAPPER_COLLECTION_CALLBACK]( $key );
785  $statsGroup = $wrapperInfo[self::WRAPPER_STATS_GROUP];
786  } else {
787  // Key came directly from BagOStuff::makeKey() or BagOStuff::makeGlobalKey()
788  // and thus has the format of "<scope>:<collection>[:<constant or variable>]..."
789  $components = explode( ':', $key, 3 );
790  // Handle legacy callers that fail to use the key building methods
791  $collection = $components[1] ?? $components[0];
792  $statsGroup = 'objectcache';
793  }
794 
795  // Replace dots because they are special in StatsD (T232907)
796  return $statsGroup . '.' . strtr( $collection, '.', '_' );
797  }
798 
804  public function getCurrentTime() {
805  return $this->wallClockOverride ?: microtime( true );
806  }
807 
813  public function setMockTime( &$time ) {
814  $this->wallClockOverride =& $time;
815  }
816 }
BagOStuff\getSegmentedValueMaxSize
getSegmentedValueMaxSize()
Definition: BagOStuff.php:583
BagOStuff\determineKeyPrefixForStats
determineKeyPrefixForStats( $key)
Definition: BagOStuff.php:778
BagOStuff\setNewPreparedValues
setNewPreparedValues(array $valueByKey)
Make a "generic" reversible cache key from the given components.
BagOStuff\registerWrapperInfoForStats
registerWrapperInfoForStats(string $prefixComponent, string $statsGroup, callable $collectionCallback)
Register info about a caching layer class that uses BagOStuff as a backing store.
Definition: BagOStuff.php:667
BagOStuff\$stats
StatsdDataFactoryInterface $stats
Definition: BagOStuff.php:88
BagOStuff\getQoS
getQoS( $flag)
Definition: BagOStuff.php:567
BagOStuff\getLastError
getLastError()
Get the "last error" registered; clearLastError() should be called manually.
BagOStuff\add
add( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
BagOStuff\WRITE_SYNC
const WRITE_SYNC
Bitfield constants for set()/merge(); these are only advisory.
Definition: BagOStuff.php:118
BagOStuff\WRITE_ALLOW_SEGMENTS
const WRITE_ALLOW_SEGMENTS
Definition: BagOStuff.php:120
Wikimedia\LightweightObjectStore\ExpirationAwareness
Generic interface providing Time-To-Live constants for expirable object storage.
Definition: ExpirationAwareness.php:32
NullStatsdDataFactory
Definition: NullStatsdDataFactory.php:10
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:86
BagOStuff\genericKeyFromComponents
genericKeyFromComponents(... $components)
At a minimum, there must be a keyspace and collection name component.
Definition: BagOStuff.php:685
BagOStuff\changeTTL
changeTTL( $key, $exptime=0, $flags=0)
Change the expiration on a key if it exists.
BagOStuff\componentsFromGenericKey
componentsFromGenericKey( $key)
Extract the components from a "generic" reversible cache key.
Definition: BagOStuff.php:711
BagOStuff\$wrapperInfoByPrefix
array< string, array > $wrapperInfoByPrefix
Cache key processing callbacks and info for metrics.
Definition: BagOStuff.php:97
BagOStuff\convertGenericKey
convertGenericKey( $key)
Convert a "generic" reversible cache key into one for this cache.
BagOStuff\$logger
LoggerInterface $logger
Definition: BagOStuff.php:90
BagOStuff\changeTTLMulti
changeTTLMulti(array $keys, $exptime, $flags=0)
Change the expiration of multiple keys that exist.
BagOStuff\setMockTime
setMockTime(&$time)
Definition: BagOStuff.php:813
BagOStuff\isKeyGlobal
isKeyGlobal( $key)
Check whether a cache key is in the global keyspace.
Definition: BagOStuff.php:558
BagOStuff\unlock
unlock( $key)
Release an advisory lock on a key string.
BagOStuff\clearLastError
clearLastError()
Clear the "last error" registry.
BagOStuff\decr
decr( $key, $value=1, $flags=0)
Decrease stored value of $key by $value while preserving its TTL.
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1034
BagOStuff\incr
incr( $key, $value=1, $flags=0)
Increase stored value of $key by $value while preserving its TTL.
BagOStuff\setLogger
setLogger(LoggerInterface $logger)
Definition: BagOStuff.php:173
BagOStuff\$asyncHandler
callable null $asyncHandler
Definition: BagOStuff.php:92
BagOStuff\proxyCall
proxyCall( $method, $arg0Sig, $resSig, array $genericArgs)
Call a method on behalf of wrapper BagOStuff instance that uses "generic" keys.
Definition: BagOStuff.php:735
BagOStuff\WRITE_BACKGROUND
const WRITE_BACKGROUND
Definition: BagOStuff.php:122
BagOStuff\READ_LATEST
const READ_LATEST
Bitfield constants for get()/getMulti(); these are only advisory.
Definition: BagOStuff.php:115
BagOStuff\addBusyCallback
addBusyCallback(callable $workCallback)
Let a callback be run to avoid wasting time on special blocking calls.
BagOStuff\$wallClockOverride
float null $wallClockOverride
Definition: BagOStuff.php:112
BagOStuff\WRITE_PRUNE_SEGMENTS
const WRITE_PRUNE_SEGMENTS
Definition: BagOStuff.php:121
Wikimedia\LightweightObjectStore\StorageAwareness
Generic interface providing error code and quality-of-service constants for object stores.
Definition: StorageAwareness.php:32
BagOStuff\getWithSetCallback
getWithSetCallback( $key, $exptime, $callback, $flags=0)
Get an item with the given key, regenerating and setting it if not found.
Definition: BagOStuff.php:206
BagOStuff\WRAPPER_STATS_GROUP
const WRAPPER_STATS_GROUP
Key to the metric group to use for the relevant cache wrapper.
Definition: BagOStuff.php:146
BagOStuff\mergeFlagMaps
mergeFlagMaps(array $bags)
Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map.
Definition: BagOStuff.php:603
BagOStuff\__construct
__construct(array $params=[])
Parameters include:
Definition: BagOStuff.php:162
BagOStuff\getLogger
getLogger()
Definition: BagOStuff.php:181
BagOStuff\makeKey
makeKey( $collection,... $components)
Make a cache key for the global keyspace and given components.
BagOStuff\merge
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
BagOStuff\deleteMulti
deleteMulti(array $keys, $flags=0)
Batch deletion.
BagOStuff\incrWithInit
incrWithInit( $key, $exptime, $value=1, $init=null, $flags=0)
Increase the value of the given key (no TTL change) if it exists or create it otherwise.
BagOStuff\makeKeyInternal
makeKeyInternal( $keyspace, $components)
Make a cache key for the given keyspace and components.
BagOStuff\setDebug
setDebug( $enabled)
Definition: BagOStuff.php:189
BagOStuff\setMulti
setMulti(array $valueByKey, $exptime=0, $flags=0)
Batch insertion/replace.
BagOStuff\$debugMode
bool $debugMode
Whether to send debug log entries to the SPI logger instance.
Definition: BagOStuff.php:109
BagOStuff\$attrMap
int[] $attrMap
Map of (ATTR_* class constant => QOS_* class constant)
Definition: BagOStuff.php:100
BagOStuff\READ_VERIFIED
const READ_VERIFIED
Definition: BagOStuff.php:116
BagOStuff\fieldHasFlags
fieldHasFlags( $field, $flags)
Definition: BagOStuff.php:593
BagOStuff\lock
lock( $key, $timeout=6, $expiry=6, $rclass='')
Acquire an advisory lock on a key string.
$keys
$keys
Definition: testCompression.php:72
BagOStuff\getCurrentTime
getCurrentTime()
Definition: BagOStuff.php:804
BagOStuff\$keyspace
string $keyspace
Default keyspace; used by makeKey()
Definition: BagOStuff.php:103
BagOStuff\deleteObjectsExpiringBefore
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF)
Delete all objects expiring before a certain date.
IStoreKeyEncoder
Generic interface for object stores with key encoding methods.
Definition: IStoreKeyEncoder.php:9
BagOStuff\getScopedLock
getScopedLock( $key, $timeout=6, $expiry=30, $rclass='')
Get a lightweight exclusive self-unlocking lock.
Definition: BagOStuff.php:350
BagOStuff\getSegmentationSize
getSegmentationSize()
Definition: BagOStuff.php:575
BagOStuff\makeGlobalKey
makeGlobalKey( $collection,... $components)
Make a cache key for the default keyspace and given components.
BagOStuff\getMulti
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
BagOStuff\WRAPPER_COLLECTION_CALLBACK
const WRAPPER_COLLECTION_CALLBACK
Key to the callback that extracts collection names from cache wrapper keys.
Definition: BagOStuff.php:148
BagOStuff\WRITE_CACHE_ONLY
const WRITE_CACHE_ONLY
Definition: BagOStuff.php:119