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 
160  public function __construct( array $params = [] ) {
161  $this->keyspace = $params['keyspace'] ?? 'local';
162  $this->asyncHandler = $params['asyncHandler'] ?? null;
163  $this->stats = $params['stats'] ?? new NullStatsdDataFactory();
164  $this->setLogger( $params['logger'] ?? new NullLogger() );
165  }
166 
171  public function setLogger( LoggerInterface $logger ) {
172  $this->logger = $logger;
173  }
174 
179  public function getLogger() : LoggerInterface {
180  return $this->logger;
181  }
182 
187  public function setDebug( $enabled ) {
188  wfDeprecated( __METHOD__, '1.36' );
189  }
190 
204  final public function getWithSetCallback( $key, $exptime, $callback, $flags = 0 ) {
205  $value = $this->get( $key, $flags );
206 
207  if ( $value === false ) {
208  $value = $callback( $exptime );
209  if ( $value !== false && $exptime >= 0 ) {
210  $this->set( $key, $value, $exptime, $flags );
211  }
212  }
213 
214  return $value;
215  }
216 
230  abstract public function get( $key, $flags = 0 );
231 
241  abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
242 
254  abstract public function delete( $key, $flags = 0 );
255 
265  abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
266 
284  abstract public function merge(
285  $key,
286  callable $callback,
287  $exptime = 0,
288  $attempts = 10,
289  $flags = 0
290  );
291 
309  abstract public function changeTTL( $key, $exptime = 0, $flags = 0 );
310 
322  abstract public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' );
323 
330  abstract public function unlock( $key );
331 
348  final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
349  $expiry = min( $expiry ?: INF, self::TTL_DAY );
350 
351  if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
352  return null;
353  }
354 
355  $lSince = $this->getCurrentTime(); // lock timestamp
356 
357  return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
358  $latency = 0.050; // latency skew (err towards keeping lock present)
359  $age = ( $this->getCurrentTime() - $lSince + $latency );
360  if ( ( $age + $latency ) >= $expiry ) {
361  $this->logger->warning(
362  "Lock for {key} held too long ({age} sec).",
363  [ 'key' => $key, 'age' => $age ]
364  );
365  return; // expired; it's not "safe" to delete the key
366  }
367  $this->unlock( $key );
368  } );
369  }
370 
381  abstract public function deleteObjectsExpiringBefore(
382  $timestamp,
383  callable $progress = null,
384  $limit = INF
385  );
386 
394  abstract public function getMulti( array $keys, $flags = 0 );
395 
409  abstract public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 );
410 
423  abstract public function deleteMulti( array $keys, $flags = 0 );
424 
436  abstract public function changeTTLMulti( array $keys, $exptime, $flags = 0 );
437 
446  abstract public function incr( $key, $value = 1, $flags = 0 );
447 
456  abstract public function decr( $key, $value = 1, $flags = 0 );
457 
473  abstract public function incrWithInit( $key, $exptime, $value = 1, $init = null, $flags = 0 );
474 
480  abstract public function getLastError();
481 
486  abstract public function clearLastError();
487 
508  abstract public function addBusyCallback( callable $workCallback );
509 
523  abstract public function makeKeyInternal( $keyspace, $components );
524 
535  abstract public function makeGlobalKey( $collection, ...$components );
536 
547  abstract public function makeKey( $collection, ...$components );
548 
556  public function isKeyGlobal( $key ) {
557  return ( strncmp( $key, self::GLOBAL_PREFIX, self::GLOBAL_PREFIX_LEN ) === 0 );
558  }
559 
565  public function getQoS( $flag ) {
566  return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
567  }
568 
573  public function getSegmentationSize() {
574  return INF;
575  }
576 
581  public function getSegmentedValueMaxSize() {
582  return INF;
583  }
584 
591  final protected function fieldHasFlags( $field, $flags ) {
592  return ( ( $field & $flags ) === $flags );
593  }
594 
601  final protected function mergeFlagMaps( array $bags ) {
602  $map = [];
603  foreach ( $bags as $bag ) {
604  foreach ( $bag->attrMap as $attr => $rank ) {
605  if ( isset( $map[$attr] ) ) {
606  $map[$attr] = min( $map[$attr], $rank );
607  } else {
608  $map[$attr] = $rank;
609  }
610  }
611  }
612 
613  return $map;
614  }
615 
641  abstract public function setNewPreparedValues( array $valueByKey );
642 
666  string $prefixComponent,
667  string $statsGroup,
668  callable $collectionCallback
669  ) {
670  $this->wrapperInfoByPrefix[$prefixComponent] = [
671  self::WRAPPER_STATS_GROUP => $statsGroup,
672  self::WRAPPER_COLLECTION_CALLBACK => $collectionCallback
673  ];
674  }
675 
683  final protected function genericKeyFromComponents( ...$components ) {
684  if ( count( $components ) < 2 ) {
685  throw new InvalidArgumentException( "Missing keyspace or collection name" );
686  }
687 
688  $key = '';
689  foreach ( $components as $component ) {
690  if ( $key !== '' ) {
691  $key .= ':';
692  }
693  // Escape delimiter (":") and escape ("%") characters
694  $key .= strtr( $component, [ '%' => '%25', ':' => '%3A' ] );
695  }
696 
697  return $key;
698  }
699 
709  final protected function componentsFromGenericKey( $key ) {
710  // Note that the order of each corresponding search/replace pair matters
711  return str_replace( [ '%3A', '%25' ], [ ':', '%' ], explode( ':', $key ) );
712  }
713 
722  abstract protected function convertGenericKey( $key );
723 
733  protected function proxyCall( $method, $arg0Sig, $resSig, array $genericArgs ) {
734  // Get the corresponding store-specific cache keys...
735  $storeArgs = $genericArgs;
736  switch ( $arg0Sig ) {
737  case self::ARG0_KEY:
738  $storeArgs[0] = $this->convertGenericKey( $genericArgs[0] );
739  break;
740  case self::ARG0_KEYARR:
741  foreach ( $genericArgs[0] as $i => $genericKey ) {
742  $storeArgs[0][$i] = $this->convertGenericKey( $genericKey );
743  }
744  break;
745  case self::ARG0_KEYMAP:
746  $storeArgs[0] = [];
747  foreach ( $genericArgs[0] as $genericKey => $v ) {
748  $storeArgs[0][$this->convertGenericKey( $genericKey )] = $v;
749  }
750  break;
751  }
752 
753  // Result of invoking the method with the corresponding store-specific cache keys
754  $storeRes = $this->$method( ...$storeArgs );
755 
756  // Convert any store-specific cache keys in the result back to generic cache keys
757  if ( $resSig === self::RES_KEYMAP ) {
758  // Map of (store-specific cache key => generic cache key)
759  $genericKeyByStoreKey = array_combine( $storeArgs[0], $genericArgs[0] );
760 
761  $genericRes = [];
762  foreach ( $storeRes as $storeKey => $value ) {
763  $genericRes[$genericKeyByStoreKey[$storeKey]] = $value;
764  }
765  } else {
766  $genericRes = $storeRes;
767  }
768 
769  return $genericRes;
770  }
771 
776  protected function determineKeyPrefixForStats( $key ) {
777  $firstComponent = substr( $key, 0, strcspn( $key, ':' ) );
778 
779  $wrapperInfo = $this->wrapperInfoByPrefix[$firstComponent] ?? null;
780  if ( $wrapperInfo ) {
781  // Key has the prefix of a cache wrapper class that wraps BagOStuff
782  $collection = $wrapperInfo[self::WRAPPER_COLLECTION_CALLBACK]( $key );
783  $statsGroup = $wrapperInfo[self::WRAPPER_STATS_GROUP];
784  } else {
785  // Key came directly from BagOStuff::makeKey() or BagOStuff::makeGlobalKey()
786  // and thus has the format of "<scope>:<collection>[:<constant or variable>]..."
787  $components = explode( ':', $key, 3 );
788  // Handle legacy callers that fail to use the key building methods
789  $collection = $components[1] ?? $components[0];
790  $statsGroup = 'objectcache';
791  }
792 
793  // Replace dots because they are special in StatsD (T232907)
794  return $statsGroup . '.' . strtr( $collection, '.', '_' );
795  }
796 
802  public function getCurrentTime() {
803  return $this->wallClockOverride ?: microtime( true );
804  }
805 
811  public function setMockTime( &$time ) {
812  $this->wallClockOverride =& $time;
813  }
814 }
BagOStuff\getSegmentedValueMaxSize
getSegmentedValueMaxSize()
Definition: BagOStuff.php:581
BagOStuff\determineKeyPrefixForStats
determineKeyPrefixForStats( $key)
Definition: BagOStuff.php:776
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:665
BagOStuff\$stats
StatsdDataFactoryInterface $stats
Definition: BagOStuff.php:88
BagOStuff\getQoS
getQoS( $flag)
Definition: BagOStuff.php:565
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:683
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:709
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:811
BagOStuff\isKeyGlobal
isKeyGlobal( $key)
Check whether a cache key is in the global keyspace.
Definition: BagOStuff.php:556
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:996
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:171
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:733
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:204
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:601
BagOStuff\__construct
__construct(array $params=[])
Parameters include:
Definition: BagOStuff.php:160
BagOStuff\getLogger
getLogger()
Definition: BagOStuff.php:179
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:187
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:591
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:802
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:348
BagOStuff\getSegmentationSize
getSegmentationSize()
Definition: BagOStuff.php:573
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