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 
323  abstract public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' );
324 
331  abstract public function unlock( $key );
332 
349  final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
350  $expiry = min( $expiry ?: INF, self::TTL_DAY );
351 
352  if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
353  return null;
354  }
355 
356  return new ScopedCallback( function () use ( $key, $expiry ) {
357  $this->unlock( $key );
358  } );
359  }
360 
373  abstract public function deleteObjectsExpiringBefore(
374  $timestamp,
375  callable $progress = null,
376  $limit = INF,
377  string $tag = null
378  );
379 
387  abstract public function getMulti( array $keys, $flags = 0 );
388 
402  abstract public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 );
403 
416  abstract public function deleteMulti( array $keys, $flags = 0 );
417 
429  abstract public function changeTTLMulti( array $keys, $exptime, $flags = 0 );
430 
439  abstract public function incr( $key, $value = 1, $flags = 0 );
440 
449  abstract public function decr( $key, $value = 1, $flags = 0 );
450 
466  abstract public function incrWithInit( $key, $exptime, $value = 1, $init = null, $flags = 0 );
467 
473  abstract public function getLastError();
474 
479  abstract public function clearLastError();
480 
501  abstract public function addBusyCallback( callable $workCallback );
502 
516  abstract public function makeKeyInternal( $keyspace, $components );
517 
528  abstract public function makeGlobalKey( $collection, ...$components );
529 
540  abstract public function makeKey( $collection, ...$components );
541 
549  public function isKeyGlobal( $key ) {
550  return ( strncmp( $key, self::GLOBAL_PREFIX, self::GLOBAL_PREFIX_LEN ) === 0 );
551  }
552 
558  public function getQoS( $flag ) {
559  return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
560  }
561 
566  public function getSegmentationSize() {
567  return INF;
568  }
569 
574  public function getSegmentedValueMaxSize() {
575  return INF;
576  }
577 
584  final protected function fieldHasFlags( $field, $flags ) {
585  return ( ( $field & $flags ) === $flags );
586  }
587 
594  final protected function mergeFlagMaps( array $bags ) {
595  $map = [];
596  foreach ( $bags as $bag ) {
597  foreach ( $bag->attrMap as $attr => $rank ) {
598  if ( isset( $map[$attr] ) ) {
599  $map[$attr] = min( $map[$attr], $rank );
600  } else {
601  $map[$attr] = $rank;
602  }
603  }
604  }
605 
606  return $map;
607  }
608 
634  abstract public function setNewPreparedValues( array $valueByKey );
635 
659  string $prefixComponent,
660  string $statsGroup,
661  callable $collectionCallback
662  ) {
663  $this->wrapperInfoByPrefix[$prefixComponent] = [
664  self::WRAPPER_STATS_GROUP => $statsGroup,
665  self::WRAPPER_COLLECTION_CALLBACK => $collectionCallback
666  ];
667  }
668 
676  final protected function genericKeyFromComponents( ...$components ) {
677  if ( count( $components ) < 2 ) {
678  throw new InvalidArgumentException( "Missing keyspace or collection name" );
679  }
680 
681  $key = '';
682  foreach ( $components as $i => $component ) {
683  if ( $i > 0 ) {
684  $key .= ':';
685  }
686  // Escape delimiter (":") and escape ("%") characters
687  $key .= strtr( $component, [ '%' => '%25', ':' => '%3A' ] );
688  }
689 
690  return $key;
691  }
692 
702  final protected function componentsFromGenericKey( $key ) {
703  // Note that the order of each corresponding search/replace pair matters
704  return str_replace( [ '%3A', '%25' ], [ ':', '%' ], explode( ':', $key ) );
705  }
706 
715  abstract protected function convertGenericKey( $key );
716 
726  protected function proxyCall( $method, $arg0Sig, $resSig, array $genericArgs ) {
727  // Get the corresponding store-specific cache keys...
728  $storeArgs = $genericArgs;
729  switch ( $arg0Sig ) {
730  case self::ARG0_KEY:
731  $storeArgs[0] = $this->convertGenericKey( $genericArgs[0] );
732  break;
733  case self::ARG0_KEYARR:
734  foreach ( $genericArgs[0] as $i => $genericKey ) {
735  $storeArgs[0][$i] = $this->convertGenericKey( $genericKey );
736  }
737  break;
738  case self::ARG0_KEYMAP:
739  $storeArgs[0] = [];
740  foreach ( $genericArgs[0] as $genericKey => $v ) {
741  $storeArgs[0][$this->convertGenericKey( $genericKey )] = $v;
742  }
743  break;
744  }
745 
746  // Result of invoking the method with the corresponding store-specific cache keys
747  $storeRes = $this->$method( ...$storeArgs );
748 
749  // Convert any store-specific cache keys in the result back to generic cache keys
750  if ( $resSig === self::RES_KEYMAP ) {
751  // Map of (store-specific cache key => generic cache key)
752  $genericKeyByStoreKey = array_combine( $storeArgs[0], $genericArgs[0] );
753 
754  $genericRes = [];
755  foreach ( $storeRes as $storeKey => $value ) {
756  $genericRes[$genericKeyByStoreKey[$storeKey]] = $value;
757  }
758  } else {
759  $genericRes = $storeRes;
760  }
761 
762  return $genericRes;
763  }
764 
769  protected function determineKeyPrefixForStats( $key ) {
770  $firstComponent = substr( $key, 0, strcspn( $key, ':' ) );
771 
772  $wrapperInfo = $this->wrapperInfoByPrefix[$firstComponent] ?? null;
773  if ( $wrapperInfo ) {
774  // Key has the prefix of a cache wrapper class that wraps BagOStuff
775  $collection = $wrapperInfo[self::WRAPPER_COLLECTION_CALLBACK]( $key );
776  $statsGroup = $wrapperInfo[self::WRAPPER_STATS_GROUP];
777  } else {
778  // Key came directly from BagOStuff::makeKey() or BagOStuff::makeGlobalKey()
779  // and thus has the format of "<scope>:<collection>[:<constant or variable>]..."
780  $components = explode( ':', $key, 3 );
781  // Handle legacy callers that fail to use the key building methods
782  $collection = $components[1] ?? $components[0];
783  $statsGroup = 'objectcache';
784  }
785 
786  // Replace dots because they are special in StatsD (T232907)
787  return $statsGroup . '.' . strtr( $collection, '.', '_' );
788  }
789 
795  public function getCurrentTime() {
796  return $this->wallClockOverride ?: microtime( true );
797  }
798 
804  public function setMockTime( &$time ) {
805  $this->wallClockOverride =& $time;
806  }
807 }
BagOStuff\getSegmentedValueMaxSize
getSegmentedValueMaxSize()
Definition: BagOStuff.php:574
BagOStuff\determineKeyPrefixForStats
determineKeyPrefixForStats( $key)
Definition: BagOStuff.php:769
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:658
BagOStuff\$stats
StatsdDataFactoryInterface $stats
Definition: BagOStuff.php:88
BagOStuff\getQoS
getQoS( $flag)
Definition: BagOStuff.php:558
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:676
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:702
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:804
BagOStuff\isKeyGlobal
isKeyGlobal( $key)
Check whether a cache key is in the global keyspace.
Definition: BagOStuff.php:549
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 a deprecated feature was used.
Definition: GlobalFunctions.php:997
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:726
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:594
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\lock
lock( $key, $timeout=6, $exptime=6, $rclass='')
Acquire an advisory lock on a key string, exclusive to the caller.
BagOStuff\fieldHasFlags
fieldHasFlags( $field, $flags)
Definition: BagOStuff.php:584
$keys
$keys
Definition: testCompression.php:72
BagOStuff\getCurrentTime
getCurrentTime()
Definition: BagOStuff.php:795
BagOStuff\$keyspace
string $keyspace
Default keyspace; used by makeKey()
Definition: BagOStuff.php:103
IStoreKeyEncoder
Generic interface for object stores with key encoding methods.
Definition: IStoreKeyEncoder.php:9
Wikimedia\LightweightObjectStore\StorageAwareness\QOS_UNKNOWN
const QOS_UNKNOWN
Generic "unknown" value; useful for comparisons (always "good enough")
Definition: StorageAwareness.php:67
BagOStuff\getScopedLock
getScopedLock( $key, $timeout=6, $expiry=30, $rclass='')
Get a lightweight exclusive self-unlocking lock.
Definition: BagOStuff.php:349
BagOStuff\getSegmentationSize
getSegmentationSize()
Definition: BagOStuff.php:566
BagOStuff\makeGlobalKey
makeGlobalKey( $collection,... $components)
Make a cache key for the default keyspace and given components.
BagOStuff\deleteObjectsExpiringBefore
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF, string $tag=null)
Delete all objects expiring before a certain date.
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