MediaWiki REL1_33
WANObjectCache Class Reference

Multi-datacenter aware caching interface. More...

Inheritance diagram for WANObjectCache:
Collaboration diagram for WANObjectCache:

Public Member Functions

 __construct (array $params)
 
 adaptiveTTL ( $mtime, $maxTTL, $minTTL=30, $factor=0.2)
 Get a TTL that is higher for objects that have not changed recently.
 
 clearLastError ()
 Clear the "last error" registry.
 
 clearProcessCache ()
 Clear the in-process caches; useful for testing.
 
 delete ( $key, $ttl=self::HOLDOFF_TTL)
 Purge a key from all datacenters.
 
 get ( $key, &$curTTL=null, array $checkKeys=[], &$info=null)
 Fetch the value of a key from cache.
 
 getCheckKeyTime ( $key)
 Fetch the value of a timestamp "check" key.
 
 getLastError ()
 Get the "last error" registered; clearLastError() should be called manually.
 
 getMulti (array $keys, &$curTTLs=[], array $checkKeys=[], &$info=null)
 Fetch the value of several keys from cache.
 
 getMultiCheckKeyTime (array $keys)
 Fetch the values of each timestamp "check" key.
 
 getMultiWithSetCallback (ArrayIterator $keyedIds, $ttl, callable $callback, array $opts=[])
 Method to fetch multiple cache keys at once with regeneration.
 
 getMultiWithUnionSetCallback (ArrayIterator $keyedIds, $ttl, callable $callback, array $opts=[])
 Method to fetch/regenerate multiple cache keys at once.
 
 getQoS ( $flag)
 
 getWarmupKeyMisses ()
 
 getWithSetCallback ( $key, $ttl, $callback, array $opts=[])
 Method to fetch/regenerate cache keys.
 
 makeGlobalKey ( $class, $component=null)
 
 makeKey ( $class, $component=null)
 
 makeMultiKeys (array $entities, callable $keyFunc)
 
 reap ( $key, $purgeTimestamp, &$isStale=false)
 Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp.
 
 reapCheckKey ( $key, $purgeTimestamp, &$isStale=false)
 Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp.
 
 resetCheckKey ( $key)
 Delete a "check" key from all datacenters, invalidating keys that use it.
 
 set ( $key, $value, $ttl=self::TTL_INDEFINITE, array $opts=[])
 Set the value of a key in cache.
 
 setLogger (LoggerInterface $logger)
 
 setMockTime (&$time)
 
 touchCheckKey ( $key, $holdoff=self::HOLDOFF_TTL)
 Purge a "check" key from all datacenters, invalidating keys that use it.
 
 useInterimHoldOffCaching ( $enabled)
 Enable or disable the use of brief caching for tombstoned keys.
 

Static Public Member Functions

static newEmpty ()
 Get an instance that wraps EmptyBagOStuff.
 

Public Attributes

const AGE_NEW = 60
 Never consider performing "popularity" refreshes until a key reaches this age.
 
const CHECK_KEY_TTL = self::TTL_YEAR
 Seconds to keep dependency purge keys around.
 
const COOLOFF_KEY_PREFIX = 'WANCache:c:'
 
const COOLOFF_TTL = 1
 Seconds to no-op key set() calls to avoid large blob I/O stampedes.
 
const FLD_FLAGS = 4
 
const FLD_HOLDOFF = 5
 
const FLD_TIME = 3
 
const FLD_TTL = 2
 
const FLD_VALUE = 1
 
const FLD_VERSION = 0
 
const GRACE_TTL_NONE = 0
 Idiom for set()/getWithSetCallback() for "no post-expired grace period".
 
const HIT_RATE_HIGH = 1
 Hits/second for a refresh to be expected within the "popularity" window.
 
const HOLDOFF_NONE = 0
 Idiom for delete() for "no hold-off".
 
const HOLDOFF_TTL = 11
 Seconds to tombstone keys on delete()
 
const HOT_TTR = 900
 The time length of the "popularity" refresh window for hot keys.
 
const INTERIM_KEY_PREFIX = 'WANCache:i:'
 
const INTERIM_KEY_TTL = 1
 Seconds to keep interim value keys for tombstoned keys around.
 
const LOCK_TTL = 10
 Seconds to keep lock keys around.
 
const LOW_TTL = 30
 Default remaining TTL at which to consider pre-emptive regeneration.
 
const MAX_COMMIT_DELAY = 3
 Max time expected to pass between delete() and DB commit finishing.
 
const MAX_READ_LAG = 7
 Max replication+snapshot lag before applying TTL_LAGGED or disallowing set()
 
const MIN_TIMESTAMP_NONE = 0.0
 Idiom for getWithSetCallback() for "no minimum required as-of timestamp".
 
const MUTEX_KEY_PREFIX = 'WANCache:m:'
 
const PASS_BY_REF = -1
 Parameter to get()/getMulti() to return extra information by reference.
 
const PC_PRIMARY = 'primary:1000'
 
const PURGE_VAL_PREFIX = 'PURGED:'
 
const RAMPUP_TTL = 30
 Seconds to ramp up to the "popularity" refresh chance after a key is no longer new.
 
const RECENT_SET_HIGH_MS = 100
 Max millisecond set() backoff for keys in hold-off (far less than INTERIM_KEY_TTL)
 
const RECENT_SET_LOW_MS = 50
 Min millisecond set() backoff for keys in hold-off (far less than INTERIM_KEY_TTL)
 
const SET_DELAY_HIGH_MS = 50
 Milliseconds of delay after get() where set() storms are a consideration with 'lockTSE'.
 
const STALE_TTL_NONE = 0
 Idiom for set()/getWithSetCallback() for "do not augment the storage medium TTL".
 
const TIME_KEY_PREFIX = 'WANCache:t:'
 
const TINY_NEGATIVE = -0.000001
 Tiny negative float to use when CTL comes up >= 0 due to clock skew.
 
const TINY_POSTIVE = 0.000001
 Tiny positive float to use when using "minTime" to assert an inequality.
 
const TSE_NONE = -1
 Idiom for getWithSetCallback() callbacks to 'lockTSE' logic.
 
const TTL_LAGGED = 30
 Max TTL to store keys when a data sourced is lagged.
 
const TTL_UNCACHEABLE = -1
 Idiom for getWithSetCallback() callbacks to avoid calling set()
 
const VALUE_KEY_PREFIX = 'WANCache:v:'
 
const VERSION = 1
 Cache format version number.
 
const VFLD_DATA = 'WOC:d'
 
const VFLD_VERSION = 'WOC:v'
 
- Public Attributes inherited from IExpiringStore
const ATTR_EMULATION = 1
 
const ATTR_SYNCWRITES = 2
 
const ERR_NO_RESPONSE = 1
 
const ERR_NONE = 0
 
const ERR_UNEXPECTED = 3
 
const ERR_UNREACHABLE = 2
 
const QOS_EMULATION_SQL = 1
 
const QOS_SYNCWRITES_BE = 2
 
const QOS_SYNCWRITES_NONE = 1
 
const QOS_SYNCWRITES_QC = 3
 
const QOS_SYNCWRITES_SS = 4
 
const QOS_UNKNOWN = INF
 
const TTL_DAY = 86400
 
const TTL_HOUR = 3600
 
const TTL_INDEFINITE = 0
 
const TTL_MINUTE = 60
 
const TTL_MONTH = 2592000
 
const TTL_PROC_LONG = 30
 
const TTL_PROC_SHORT = 3
 
const TTL_SECOND = 1
 
const TTL_WEEK = 604800
 
const TTL_YEAR = 31536000
 

Protected Member Functions

 determineKeyClassForStats ( $key)
 
 doGetWithSetCallback ( $key, $ttl, $callback, array $opts, &$asOf=null)
 Do the actual I/O for getWithSetCallback() when needed.
 
 getCurrentTime ()
 
 getInterimValue ( $key, $versioned, $minTime)
 
 getProcessCache ( $group)
 
 isAliveOrInGracePeriod ( $curTTL, $graceTTL)
 Check if a key is fresh or in the grace window and thus due for randomized reuse.
 
 isValid ( $value, $versioned, $asOf, $minTime, $purgeTime=null)
 Check if $value is not false, versioned (if needed), and not older than $minTime (if set)
 
 makePurgeValue ( $timestamp, $holdoff)
 
 parsePurgeValue ( $value)
 
 relayDelete ( $key)
 Do the actual async bus delete of a key.
 
 relayPurge ( $key, $ttl, $holdoff)
 Do the actual async bus purge of a key.
 
 resolveCTL ( $value, $curTTL, $curInfo, $touchedCallback)
 
 resolveTouched ( $value, $lastPurge, $touchedCallback)
 
 setInterimValue ( $key, $value, $tempTTL, $newAsOf)
 
 unwrap ( $wrapped, $now)
 Do not use this method outside WANObjectCache.
 
 worthRefreshExpiring ( $curTTL, $lowTTL)
 Check if a key is nearing expiration and thus due for randomized regeneration.
 
 worthRefreshPopular ( $asOf, $ageNew, $timeTillRefresh, $now)
 Check if a key is due for randomized regeneration due to its popularity.
 
 wrap ( $value, $ttl, $now)
 Do not use this method outside WANObjectCache.
 

Static Protected Member Functions

static prefixCacheKeys (array $keys, $prefix)
 

Protected Attributes

callable null $asyncHandler
 Function that takes a WAN cache callback and runs it later.
 
BagOStuff $cache
 The local datacenter cache.
 
string $cluster
 Cache cluster name for mcrouter use.
 
float $epoch
 Unix timestamp of the oldest possible valid values.
 
LoggerInterface $logger
 
 $mcrouterAware
 @bar bool Whether to use mcrouter key prefixing for routing
 
MapCacheLRU[] $processCaches = []
 Map of group PHP instance caches.
 
string $region
 Physical region for mcrouter use.
 
StatsdDataFactoryInterface $stats
 
bool $useInterimHoldOffCaching = true
 Whether to use "interim" caching while keys are tombstoned.
 

Private Member Functions

 checkAndSetCooloff ( $key, $kClass, $elapsed, $lockTSE, $hasLock)
 
 getNonProcessCachedKeys (array $keys, array $opts, $pcTTL)
 
 getRawKeysForWarmup (array $keys, array $checkKeys)
 
 isVolatileValueAgeNegligible ( $age)
 
 processCheckKeys (array $timeKeys, array $wrappedValues, $now)
 
 scheduleAsyncRefresh ( $key, $ttl, $callback, $opts)
 

Private Attributes

int $callbackDepth = 0
 Callback stack depth for getWithSetCallback()
 
float null $wallClockOverride
 
mixed[] $warmupCache = []
 Temporary warm-up cache.
 
int $warmupKeyMisses = 0
 Key fetched.
 

Detailed Description

Multi-datacenter aware caching interface.

Using WANObjectCache

All operations go to the local datacenter cache, except for delete(), touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.

This class is intended for caching data from primary stores. If the get() method does not return a value, then the caller should query the new value and backfill the cache using set(). The preferred way to do this logic is through getWithSetCallback(). When querying the store on cache miss, the closest DB replica should be used. Try to avoid heavyweight DB master or quorum reads.

To ensure consumers of the cache see new values in a timely manner, you either need to follow either the validation strategy, or the purge strategy.

The validation strategy refers to the natural avoidance of stale data by one of the following means:

  • A) The cached value is immutable. If the consumer has access to an identifier that uniquely describes a value, cached value need not change. Instead, the key can change. This also allows all servers to access their perceived current version. This is important in context of multiple deployed versions of your application and/or cross-dc database replication, to ensure deterministic values without oscillation.
  • B) Validity is checked against the source after get(). This is the inverse of A. The unique identifier is embedded inside the value and validated after on retreival. If outdated, the value is recomputed.
  • C) The value is cached with a modest TTL (without validation). If value recomputation is reasonably performant, and the value is allowed to be stale, one should consider using TTL only – using the value's age as method of validation.

The purge strategy refers to the the approach whereby your application knows that source data has changed and can react by purging the relevant cache keys. As purges are expensive, this strategy should be avoided if possible. The simplest purge method is delete().

No matter which strategy you choose, callers must not rely on updates or purges being immediately visible to other servers. It should be treated similarly as one would a database replica.

The need for immediate updates should be avoided. If needed, solutions must be sought outside WANObjectCache.

Deploying WANObjectCache

There are two supported ways to set up broadcasted operations:

Broadcasted operations like delete() and touchCheckKey() are intended to run immediately in the local datacenter and asynchronously in remote datacenters.

This means that callers in all datacenters may see older values for however many milliseconds that the purge took to reach that datacenter. As with any cache, this should not be relied on for cases where reads are used to determine writes to source (e.g. non-cache) data stores, except when reading immutable data.

All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix to avoid collisions with keys that are not wrapped as metadata arrays. The prefixes are as follows:

  • a) "WANCache:v" : used for regular value keys
  • b) "WANCache:i" : used for temporarily storing values of tombstoned keys
  • c) "WANCache:t" : used for storing timestamp "check" keys
  • d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
Since
1.26

Definition at line 116 of file WANObjectCache.php.

Constructor & Destructor Documentation

◆ __construct()

WANObjectCache::__construct ( array  $params)
Parameters
array$params
  • cache : BagOStuff object for a persistent cache
  • logger : LoggerInterface object
  • stats : StatsdDataFactoryInterface object
  • asyncHandler : A function that takes a callback and runs it later. If supplied, whenever a preemptive refresh would be triggered in getWithSetCallback(), the current cache value is still used instead. However, the async-handler function receives a WAN cache callback that, when run, will execute the value generation callback supplied by the getWithSetCallback() caller. The result will be saved as normal. The handler is expected to call the WAN cache callback at an opportune time (e.g. HTTP post-send), though generally within a few 100ms. [optional]
  • region: the current physical region. This is required when using mcrouter as the backing store proxy. [optional]
  • cluster: name of the cache cluster used by this WAN cache. The name must be the same in all datacenters; the ("region","cluster") tuple is what distinguishes the counterpart cache clusters among all the datacenter. The contents of https://github.com/facebook/mcrouter/wiki/Config-Files give background on this. This is required when using mcrouter as the backing store proxy. [optional]
  • mcrouterAware: set as true if mcrouter is the backing store proxy and mcrouter is configured to interpret /<region>/<cluster>/ key prefixes as routes. This requires that "region" and "cluster" are both set above. [optional]
  • epoch: lowest UNIX timestamp a value/tombstone must have to be valid. [optional]

Definition at line 254 of file WANObjectCache.php.

References $params, cache, and setLogger().

Member Function Documentation

◆ adaptiveTTL()

WANObjectCache::adaptiveTTL (   $mtime,
  $maxTTL,
  $minTTL = 30,
  $factor = 0.2 
)

Get a TTL that is higher for objects that have not changed recently.

This is useful for keys that get explicit purges and DB or purge relay lag is a potential concern (especially how it interacts with CDN cache)

Example usage:

// Last-modified time of page
$mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
// Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
// defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
// $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
$ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
$cache
Definition mcc.php:33

Another use case is when there are no applicable "last modified" fields in the DB, and there are too many dependencies for explicit purges to be viable, and the rate of change to relevant content is unstable, and it is highly valued to have the cached value be as up-to-date as possible.

Example usage:

$query = "<some complex query>";
$idListFromComplexQuery = $cache->getWithSetCallback(
$cache->makeKey( 'complex-graph-query', $hashOfQuery ),
GraphQueryClass::STARTING_TTL,
function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
$gdb = $this->getReplicaGraphDbConnection();
// Account for any snapshot/replica DB lag
$setOpts += GraphDatabase::getCacheSetOptions( $gdb );
$newList = iterator_to_array( $gdb->query( $query ) );
sort( $newList, SORT_NUMERIC ); // normalize
$minTTL = GraphQueryClass::MIN_TTL;
$maxTTL = GraphQueryClass::MAX_TTL;
if ( $oldValue !== false ) {
// Note that $oldAsOf is the last time this callback ran
$ttl = ( $newList === $oldValue )
// No change: cache for 150% of the age of $oldValue
? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
// Changed: cache for 50% of the age of $oldValue
: $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
}
return $newList;
},
[
// Keep stale values around for doing comparisons for TTL calculations.
// High values improve long-tail keys hit-rates, though might waste space.
'staleTTL' => GraphQueryClass::GRACE_TTL
]
);
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition hooks.txt:1617
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback function
Definition injection.txt:30
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
Parameters
int | float$mtimeUNIX timestamp
int$maxTTLMaximum TTL (seconds)
int$minTTLMinimum TTL (seconds); Default: 30
float$factorValue in the range (0,1); Default: .2
Returns
int Adaptive TTL
Since
1.28

Definition at line 2033 of file WANObjectCache.php.

References getCurrentTime().

◆ checkAndSetCooloff()

WANObjectCache::checkAndSetCooloff (   $key,
  $kClass,
  $elapsed,
  $lockTSE,
  $hasLock 
)
private
Parameters
string$key
string$kClass
float$elapsedSeconds spent regenerating the value
float$lockTSE
$hasLockbool
Returns
bool Whether it is OK to proceed with a key set operation

Definition at line 1470 of file WANObjectCache.php.

References cache, and IExpiringStore\ERR_NONE.

Referenced by doGetWithSetCallback().

◆ clearLastError()

WANObjectCache::clearLastError ( )
final

Clear the "last error" registry.

Definition at line 1924 of file WANObjectCache.php.

References cache.

◆ clearProcessCache()

WANObjectCache::clearProcessCache ( )

Clear the in-process caches; useful for testing.

Since
1.27

Definition at line 1933 of file WANObjectCache.php.

◆ delete()

WANObjectCache::delete (   $key,
  $ttl = self::HOLDOFF_TTL 
)
final

Purge a key from all datacenters.

This should only be called when the underlying data (being cached) changes in a significant way. This deletes the key and starts a hold-off period where the key cannot be written to for a few seconds (HOLDOFF_TTL). This is done to avoid the following race condition:

  • a) Some DB data changes and delete() is called on a corresponding key
  • b) A request refills the key with a stale value from a lagged DB
  • c) The stale value is stuck there until the key is expired/evicted

This is implemented by storing a special "tombstone" value at the cache key that this class recognizes; get() calls will return false for the key and any set() calls will refuse to replace tombstone values at the key. For this to always avoid stale value writes, the following must hold:

  • a) Replication lag is bounded to being less than HOLDOFF_TTL; or
  • b) If lag is higher, the DB will have gone into read-only mode already

Note that set() can also be lag-aware and lower the TTL if it's high.

Be aware that this does not clear the process cache. Even if it did, callbacks used by getWithSetCallback() might still return stale data in the case of either uncommitted or not-yet-replicated changes (callback generally use replica DBs).

When using potentially long-running ACID transactions, a good pattern is to use a pre-commit hook to issue the delete. This means that immediately after commit, callers will see the tombstone in cache upon purge relay. It also avoids the following race condition:

  • a) T1 begins, changes a row, and calls delete()
  • b) The HOLDOFF_TTL passes, expiring the delete() tombstone
  • c) T2 starts, reads the row and calls set() due to a cache miss
  • d) T1 finally commits
  • e) Stale value is stuck in cache

Example usage:

$dbw->startAtomic( __METHOD__ ); // start of request
... <execute some stuff> ...
// Update the row in the DB
$dbw->update( ... );
$key = $cache->makeKey( 'homes', $homeId );
// Purge the corresponding cache entry just before committing
$dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
$cache->delete( $key );
} );
... <execute some stuff> ...
$dbw->endAtomic( __METHOD__ ); // end of request
$batch execute()

The $ttl parameter can be used when purging values that have not actually changed recently. For example, a cleanup script to purge cache entries does not really need a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge. Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().

If called twice on the same key, then the last hold-off TTL takes precedence. For idempotence, the $ttl should not vary for different delete() calls on the same key.

Parameters
string$keyCache key
int$ttlTombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
Returns
bool True if the item was purged or not found, false on failure

Definition at line 703 of file WANObjectCache.php.

References determineKeyClassForStats(), relayDelete(), and relayPurge().

Referenced by WANObjectCacheTest\testBusyValue(), WANObjectCacheTest\testGetMultiWithSetCallback(), WANObjectCacheTest\testGetMultiWithUnionSetCallback(), WANObjectCacheTest\testGetWithSetCallback(), WANObjectCacheTest\testGetWithSetCallback_versions(), WANObjectCacheTest\testInterimHoldOffCaching(), and WANObjectCacheTest\testLockTSE().

◆ determineKeyClassForStats()

WANObjectCache::determineKeyClassForStats (   $key)
protected
Parameters
string$keyString of the format <scope>:<class>[:<class or variable>]...
Returns
string A collection name to describe this class of key

Definition at line 2327 of file WANObjectCache.php.

Referenced by delete(), doGetWithSetCallback(), resetCheckKey(), and touchCheckKey().

◆ doGetWithSetCallback()

WANObjectCache::doGetWithSetCallback (   $key,
  $ttl,
  $callback,
array  $opts,
$asOf = null 
)
protected

Do the actual I/O for getWithSetCallback() when needed.

See also
WANObjectCache::getWithSetCallback()
Parameters
string$key
int$ttl
callable$callback
array$optsOptions map for getWithSetCallback()
float | null&$asOfCache generation timestamp of returned value [returned]
Returns
mixed
Note
Callable type hints are not used to avoid class-autoloading

Definition at line 1300 of file WANObjectCache.php.

References $value, cache, checkAndSetCooloff(), determineKeyClassForStats(), false, getCurrentTime(), getInterimValue(), isAliveOrInGracePeriod(), isValid(), isVolatileValueAgeNegligible(), list, null, resolveCTL(), resolveTouched(), scheduleAsyncRefresh(), setInterimValue(), worthRefreshExpiring(), and worthRefreshPopular().

Referenced by getWithSetCallback(), and scheduleAsyncRefresh().

◆ get()

WANObjectCache::get (   $key,
$curTTL = null,
array  $checkKeys = [],
$info = null 
)
final

Fetch the value of a key from cache.

If supplied, $curTTL is set to the remaining TTL (current time left):

  • a) INF; if $key exists, has no TTL, and is not invalidated by $checkKeys
  • b) float (>=0); if $key exists, has a TTL, and is not invalidated by $checkKeys
  • c) float (<0); if $key is tombstoned, stale, or existing but invalidated by $checkKeys
  • d) null; if $key does not exist and is not tombstoned

If a key is tombstoned, $curTTL will reflect the time since delete().

The timestamp of $key will be checked against the last-purge timestamp of each of $checkKeys. Those $checkKeys not in cache will have the last-purge initialized to the current timestamp. If any of $checkKeys have a timestamp greater than that of $key, then $curTTL will reflect how long ago $key became invalid. Callers can use $curTTL to know when the value is stale. The $checkKeys parameter allow mass invalidations by updating a single key:

  • a) Each "check" key represents "last purged" of some source data
  • b) Callers pass in relevant "check" keys as $checkKeys in get()
  • c) When the source data that "check" keys represent changes, the touchCheckKey() method is called on them

Source data entities might exists in a DB that uses snapshot isolation (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that isolation can largely be maintained by doing the following:

  • a) Calling delete() on entity change and creation, before DB commit
  • b) Keeping transaction duration shorter than the delete() hold-off TTL
  • c) Disabling interim key caching via useInterimHoldOffCaching() before get() calls

However, pre-snapshot values might still be seen if an update was made in a remote datacenter but the purge from delete() didn't relay yet.

Consider using getWithSetCallback() instead of get() and set() cycles. That method has cache slam avoiding features for hot/expensive keys.

Pass $info as WANObjectCache::PASS_BY_REF to transform it into a cache key info map. This map includes the following metadata:

  • asOf: UNIX timestamp of the value or null if the key is nonexistant
  • tombAsOf: UNIX timestamp of the tombstone or null if the key is not tombstoned
  • lastCKPurge: UNIX timestamp of the highest check key or null if none provided

Otherwise, $info will transform into the cached value timestamp.

Parameters
string$keyCache key made from makeKey() or makeGlobalKey()
mixed | null&$curTTLApproximate TTL left on the key if present/tombstoned [returned]
array$checkKeysList of "check" keys
mixed | null&$infoKey info if WANObjectCache::PASS_BY_REF [returned]
Returns
mixed Value of cache key or false on failure

Definition at line 331 of file WANObjectCache.php.

References getMulti(), and null.

Referenced by JobQueueDB\doDeduplicateRootJob(), WANObjectCacheTest\testCheckKeyInitHoldoff(), WANObjectCacheTest\testEpoch(), WANObjectCacheTest\testGetMultiWithSetCallback(), WANObjectCacheTest\testGetMultiWithUnionSetCallback(), WANObjectCacheTest\testGetWithSetCallback(), and WANObjectCacheTest\testLockTSESlow().

◆ getCheckKeyTime()

WANObjectCache::getCheckKeyTime (   $key)
final

Fetch the value of a timestamp "check" key.

The key will be initialized to the current time if not set, so only call this method if this behavior is actually desired

The timestamp can be used to check whether a cached value is valid. Callers should not assume that this returns the same timestamp in all datacenters due to relay delays.

The level of staleness can roughly be estimated from this key, but if the key was evicted from cache, such calculations may show the time since expiry as ~0 seconds.

Note that "check" keys won't collide with other regular keys.

Parameters
string$key
Returns
float UNIX timestamp

Definition at line 737 of file WANObjectCache.php.

References getMultiCheckKeyTime().

Referenced by WANObjectCacheTest\testEpoch(), WANObjectCacheTest\testGetMulti(), WANObjectCacheTest\testGetMultiWithSetCallback(), WANObjectCacheTest\testGetMultiWithUnionSetCallback(), WANObjectCacheTest\testGetWithSetCallback(), and WANObjectCacheTest\testTouchKeys().

◆ getCurrentTime()

WANObjectCache::getCurrentTime ( )
protected
Returns
float UNIX timestamp

Definition at line 2448 of file WANObjectCache.php.

Referenced by adaptiveTTL(), doGetWithSetCallback(), getInterimValue(), getMulti(), getMultiCheckKeyTime(), relayPurge(), and set().

◆ getInterimValue()

WANObjectCache::getInterimValue (   $key,
  $versioned,
  $minTime 
)
protected
Parameters
string$key
bool$versioned
float$minTime
Returns
array (cached value or false, cached value timestamp or null)

Definition at line 1547 of file WANObjectCache.php.

References $value, cache, getCurrentTime(), isValid(), list, null, unwrap(), and useInterimHoldOffCaching().

Referenced by doGetWithSetCallback().

◆ getLastError()

WANObjectCache::getLastError ( )
final

Get the "last error" registered; clearLastError() should be called manually.

Returns
int ERR_* class constant for the "last error" registry

Definition at line 1907 of file WANObjectCache.php.

References $code, cache, IExpiringStore\ERR_NO_RESPONSE, IExpiringStore\ERR_NONE, and IExpiringStore\ERR_UNREACHABLE.

◆ getMulti()

WANObjectCache::getMulti ( array  $keys,
$curTTLs = [],
array  $checkKeys = [],
$info = null 
)
final

Fetch the value of several keys from cache.

Pass $info as WANObjectCache::PASS_BY_REF to transform it into a map of cache keys to cache key info maps, each having the same style as those of WANObjectCache::get(). All the cache keys listed in $keys will have an entry.

Othwerwise, $info will transform into a map of (cache key => cached value timestamp). Only the cache keys listed in $keys that exists or are tombstoned will have an entry.

See also
WANObjectCache::get()
Parameters
array$keysList of cache keys made from makeKey() or makeGlobalKey()
mixed | null&$curTTLsMap of (key => TTL left) for existing/tombstoned keys [returned]
array$checkKeysList of check keys to apply to all $keys. May also apply "check" keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
mixed | null&$infoMap of (key => info) if WANObjectCache::PASS_BY_REF [returned]
Returns
array Map of (key => value) for keys that exist and are not tombstoned

Definition at line 370 of file WANObjectCache.php.

References $keys, $value, array(), as, cache, getCurrentTime(), list, null, processCheckKeys(), and unwrap().

Referenced by get(), getMultiWithUnionSetCallback(), WANObjectCacheTest\testGetMulti(), and WANObjectCacheTest\testGetMultiCheckKeys().

◆ getMultiCheckKeyTime()

WANObjectCache::getMultiCheckKeyTime ( array  $keys)
final

Fetch the values of each timestamp "check" key.

This works like getCheckKeyTime() except it takes a list of keys and returns a map of timestamps instead of just that of one key

This might be useful if both:

  • a) a class of entities each depend on hundreds of other entities
  • b) these other entities are depended upon by millions of entities

The later entities can each use a "check" key to invalidate their dependee entities. However, it is expensive for the former entities to verify against all of the relevant "check" keys during each getWithSetCallback() call. A less expensive approach is to do these verifications only after a "time-till-verify" (TTV) has passed. This is a middle ground between using blind TTLs and using constant verification. The adaptiveTTL() method can be used to dynamically adjust the TTV. Also, the initial TTV can make use of the last-modified times of the dependant entities (either from the DB or the "check" keys).

Example usage:

$value = $cache->getWithSetCallback(
$cache->makeGlobalKey( 'wikibase-item', $id ),
self::INITIAL_TTV, // initial time-till-verify
function ( $oldValue, &$ttv, &$setOpts, $oldAsOf ) use ( $checkKeys, $cache ) {
$now = microtime( true );
// Use $oldValue if it passes max ultimate age and "check" key comparisons
if ( $oldValue &&
$oldAsOf > max( $cache->getMultiCheckKeyTime( $checkKeys ) ) &&
( $now - $oldValue['ctime'] ) <= self::MAX_CACHE_AGE
) {
// Increase time-till-verify by 50% of last time to reduce overhead
$ttv = $cache->adaptiveTTL( $oldAsOf, self::MAX_TTV, self::MIN_TTV, 1.5 );
// Unlike $oldAsOf, "ctime" is the ultimate age of the cached data
return $oldValue;
}
$mtimes = []; // dependency last-modified times; passed by reference
$value = [ 'data' => $this->fetchEntityData( $mtimes ), 'ctime' => $now ];
// Guess time-till-change among the dependencies, e.g. 1/(total change rate)
$ttc = 1 / array_sum( array_map(
function ( $mtime ) use ( $now ) {
return 1 / ( $mtime ? ( $now - $mtime ) : 900 );
},
$mtimes
) );
// The time-to-verify should not be overly pessimistic nor optimistic
$ttv = min( max( $ttc, self::MIN_TTV ), self::MAX_TTV );
return $value;
},
[ 'staleTTL' => $cache::TTL_DAY ] // keep around to verify and re-save
);
See also
WANObjectCache::getCheckKeyTime()
WANObjectCache::getWithSetCallback()
Parameters
array$keys
Returns
float[] Map of (key => UNIX timestamp)
Since
1.31

Definition at line 802 of file WANObjectCache.php.

References $keys, $time, as, cache, getCurrentTime(), makePurgeValue(), parsePurgeValue(), and string.

Referenced by getCheckKeyTime().

◆ getMultiWithSetCallback()

WANObjectCache::getMultiWithSetCallback ( ArrayIterator  $keyedIds,
  $ttl,
callable  $callback,
array  $opts = [] 
)
final

Method to fetch multiple cache keys at once with regeneration.

This works the same as getWithSetCallback() except:

  • a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
  • b) The $callback argument expects a callback taking the following arguments:
    • $id: ID of an entity to query
    • $oldValue : the prior cache value or false if none was present
    • &$ttl : a reference to the new value TTL in seconds
    • &$setOpts : a reference to options for set() which can be altered
    • $oldAsOf : generation UNIX timestamp of $oldValue or null if not present Aside from the additional $id argument, the other arguments function the same way they do in getWithSetCallback().
  • c) The return value is a map of (cache key => value) in the order of $keyedIds
See also
WANObjectCache::getWithSetCallback()
WANObjectCache::getMultiWithUnionSetCallback()

Example usage:

$rows = $cache->getMultiWithSetCallback(
// Map of cache keys to entity IDs
$cache->makeMultiKeys(
$this->fileVersionIds(),
return $cache->makeKey( 'file-version', $id );
}
),
// Time-to-live (in seconds)
$cache::TTL_DAY,
// Function that derives the new key value
function ( $id, $oldValue, &$ttl, array &$setOpts ) {
// Account for any snapshot/replica DB lag
$setOpts += Database::getCacheSetOptions( $dbr );
// Load the row for this file
$queryInfo = File::getQueryInfo();
$row = $dbr->selectRow(
$queryInfo['tables'],
$queryInfo['fields'],
[ 'id' => $id ],
__METHOD__,
[],
$queryInfo['joins']
);
return $row ? (array)$row : false;
},
[
// Process cache for 30 seconds
'pcTTL' => 30,
// Use a dedicated 500 item cache (initialized on-the-fly)
'pcGroup' => 'file-versions:500'
]
);
$files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Multi-datacenter aware caching interface.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
Definition hooks.txt:2818
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
const DB_REPLICA
Definition defines.php:25
Parameters
ArrayIterator$keyedIdsResult of WANObjectCache::makeMultiKeys()
int$ttlSeconds to live for key updates
callable$callbackCallback the yields entity regeneration callbacks
array$optsOptions map
Returns
array Map of (cache key => value) in the same order as $keyedIds
Since
1.28

Definition at line 1647 of file WANObjectCache.php.

References as, getNonProcessCachedKeys(), getRawKeysForWarmup(), getWithSetCallback(), and use.

Referenced by WANObjectCacheTest\testGetMultiWithSetCallback().

◆ getMultiWithUnionSetCallback()

WANObjectCache::getMultiWithUnionSetCallback ( ArrayIterator  $keyedIds,
  $ttl,
callable  $callback,
array  $opts = [] 
)
final

Method to fetch/regenerate multiple cache keys at once.

This works the same as getWithSetCallback() except:

  • a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
  • b) The $callback argument expects a callback returning a map of (ID => new value) for all entity IDs in $ids and it takes the following arguments:
    • $ids: a list of entity IDs that require cache regeneration
    • &$ttls: a reference to the (entity ID => new TTL) map
    • &$setOpts: a reference to options for set() which can be altered
  • c) The return value is a map of (cache key => value) in the order of $keyedIds
  • d) The "lockTSE" and "busyValue" options are ignored
See also
WANObjectCache::getWithSetCallback()
WANObjectCache::getMultiWithSetCallback()

Example usage:

$rows = $cache->getMultiWithUnionSetCallback(
// Map of cache keys to entity IDs
$cache->makeMultiKeys(
$this->fileVersionIds(),
return $cache->makeKey( 'file-version', $id );
}
),
// Time-to-live (in seconds)
$cache::TTL_DAY,
// Function that derives the new key value
function ( array $ids, array &$ttls, array &$setOpts ) {
// Account for any snapshot/replica DB lag
$setOpts += Database::getCacheSetOptions( $dbr );
// Load the rows for these files
$rows = [];
$queryInfo = File::getQueryInfo();
$res = $dbr->select(
$queryInfo['tables'],
$queryInfo['fields'],
[ 'id' => $ids ],
__METHOD__,
[],
$queryInfo['joins']
);
foreach ( $res as $row ) {
$rows[$row->id] = $row;
$mtime = wfTimestamp( TS_UNIX, $row->timestamp );
$ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
}
return $rows;
},
]
);
$files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
$res
Definition database.txt:21
Parameters
ArrayIterator$keyedIdsResult of WANObjectCache::makeMultiKeys()
int$ttlSeconds to live for key updates
callable$callbackCallback the yields entity regeneration callbacks
array$optsOptions map
Returns
array Map of (cache key => value) in the same order as $keyedIds
Since
1.30

Definition at line 1742 of file WANObjectCache.php.

References as, getMulti(), getNonProcessCachedKeys(), getRawKeysForWarmup(), getWithSetCallback(), and use.

Referenced by WANObjectCacheTest\testGetMultiWithUnionSetCallback().

◆ getNonProcessCachedKeys()

WANObjectCache::getNonProcessCachedKeys ( array  $keys,
array  $opts,
  $pcTTL 
)
private
Parameters
array$keys
array$opts
int$pcTTL
Returns
array List of keys

Definition at line 2394 of file WANObjectCache.php.

References $keys, as, and getProcessCache().

Referenced by getMultiWithSetCallback(), and getMultiWithUnionSetCallback().

◆ getProcessCache()

WANObjectCache::getProcessCache (   $group)
protected
Parameters
string$group
Returns
MapCacheLRU

Definition at line 2379 of file WANObjectCache.php.

References list.

Referenced by getNonProcessCachedKeys(), and getWithSetCallback().

◆ getQoS()

WANObjectCache::getQoS (   $flag)
Parameters
int$flagATTR_* class constant
Returns
int QOS_* class constant
Since
1.28

Definition at line 1966 of file WANObjectCache.php.

References cache.

Referenced by MWLBFactory\applyDefaultCaching().

◆ getRawKeysForWarmup()

WANObjectCache::getRawKeysForWarmup ( array  $keys,
array  $checkKeys 
)
private
Parameters
array$keys
array$checkKeys
Returns
array Map of (cache key => mixed)

Definition at line 2414 of file WANObjectCache.php.

References $keys, $warmupCache, as, and cache.

Referenced by getMultiWithSetCallback(), and getMultiWithUnionSetCallback().

◆ getWarmupKeyMisses()

WANObjectCache::getWarmupKeyMisses ( )
final
Returns
int Number of warmup key cache misses last round
Since
1.30

Definition at line 2051 of file WANObjectCache.php.

Referenced by WANObjectCacheTest\testGetMultiWithSetCallback(), and WANObjectCacheTest\testGetMultiWithUnionSetCallback().

◆ getWithSetCallback()

WANObjectCache::getWithSetCallback (   $key,
  $ttl,
  $callback,
array  $opts = [] 
)
final

Method to fetch/regenerate cache keys.

On cache miss, the key will be set to the callback result via set() (unless the callback returns false) and that result will be returned. The arguments supplied to the callback are:

  • $oldValue : current cache value or false if not present
  • &$ttl : a reference to the TTL which can be altered
  • &$setOpts : a reference to options for set() which can be altered
  • $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)

It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions that can cause stale values to get stuck at keys. Usually, callbacks ignore the current value, but it can be used to maintain "most recent X" values that come from time or sequence based source data, provided that the "as of" id/time is tracked. Note that preemptive regeneration and $checkKeys can result in a non-false current value.

Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache regeneration will automatically be triggered using the callback.

The $ttl argument and "hotTTR" option (in $opts) use time-dependant randomization to avoid stampedes. Keys that are slow to regenerate and either heavily used or subject to explicit (unpredictable) purges, may need additional mechanisms. The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts). If explicit purges are needed, also:

  • a) Pass $key into $checkKeys
  • b) Use touchCheckKey( $key ) instead of delete( $key )

Example usage (typical key):

$catInfo = $cache->getWithSetCallback(
// Key to store the cached value under
$cache->makeKey( 'cat-attributes', $catId ),
// Time-to-live (in seconds)
$cache::TTL_MINUTE,
// Function that derives the new key value
function ( $oldValue, &$ttl, array &$setOpts ) {
// Account for any snapshot/replica DB lag
$setOpts += Database::getCacheSetOptions( $dbr );
return $dbr->selectRow( ... );
}
);

Example usage (key that is expensive and hot):

$catConfig = $cache->getWithSetCallback(
// Key to store the cached value under
$cache->makeKey( 'site-cat-config' ),
// Time-to-live (in seconds)
$cache::TTL_DAY,
// Function that derives the new key value
function ( $oldValue, &$ttl, array &$setOpts ) {
// Account for any snapshot/replica DB lag
$setOpts += Database::getCacheSetOptions( $dbr );
return CatConfig::newFromRow( $dbr->selectRow( ... ) );
},
[
// Calling touchCheckKey() on this key invalidates the cache
'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
// Try to only let one datacenter thread manage cache updates at a time
'lockTSE' => 30,
// Avoid querying cache servers multiple times in a web request
'pcTTL' => $cache::TTL_PROC_LONG
]
);

Example usage (key with dynamic dependencies):

$catState = $cache->getWithSetCallback(
// Key to store the cached value under
$cache->makeKey( 'cat-state', $cat->getId() ),
// Time-to-live (seconds)
$cache::TTL_HOUR,
// Function that derives the new key value
function ( $oldValue, &$ttl, array &$setOpts ) {
// Determine new value from the DB
// Account for any snapshot/replica DB lag
$setOpts += Database::getCacheSetOptions( $dbr );
return CatState::newFromResults( $dbr->select( ... ) );
},
[
// The "check" keys that represent things the value depends on;
// Calling touchCheckKey() on any of them invalidates the cache
'checkKeys' => [
$cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
$cache->makeKey( 'people-present', $cat->getHouseId() ),
$cache->makeKey( 'cat-laws', $cat->getCityId() ),
]
]
);

Example usage (key that is expensive with too many DB dependencies for "check keys"):

$catToys = $cache->getWithSetCallback(
// Key to store the cached value under
$cache->makeKey( 'cat-toys', $catId ),
// Time-to-live (seconds)
$cache::TTL_HOUR,
// Function that derives the new key value
function ( $oldValue, &$ttl, array &$setOpts ) {
// Determine new value from the DB
// Account for any snapshot/replica DB lag
$setOpts += Database::getCacheSetOptions( $dbr );
return CatToys::newFromResults( $dbr->select( ... ) );
},
[
// Get the highest timestamp of any of the cat's toys
'touchedCallback' => function ( $value ) use ( $catId ) {
$ts = $dbr->selectField( 'cat_toys', 'MAX(ct_touched)', ... );
return wfTimestampOrNull( TS_UNIX, $ts );
},
// Avoid DB queries for repeated access
'pcTTL' => $cache::TTL_PROC_SHORT
]
);
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.

Example usage (hot key holding most recent 100 events):

$lastCatActions = $cache->getWithSetCallback(
// Key to store the cached value under
$cache->makeKey( 'cat-last-actions', 100 ),
// Time-to-live (in seconds)
10,
// Function that derives the new key value
function ( $oldValue, &$ttl, array &$setOpts ) {
// Account for any snapshot/replica DB lag
$setOpts += Database::getCacheSetOptions( $dbr );
// Start off with the last cached list
$list = $oldValue ?: [];
// Fetch the last 100 relevant rows in descending order;
// only fetch rows newer than $list[0] to reduce scanning
$rows = iterator_to_array( $dbr->select( ... ) );
// Merge them and get the new "last 100" rows
return array_slice( array_merge( $new, $list ), 0, 100 );
},
[
// Try to only let one datacenter thread manage cache updates at a time
'lockTSE' => 30,
// Use a magic value when no cache value is ready rather than stampeding
'busyValue' => 'computing'
]
);

Example usage (key holding an LRU subkey:value map; this can avoid flooding cache with keys for an unlimited set of (constraint,situation) pairs, thereby avoiding elevated cache evictions and wasted memory):

$catSituationTolerabilityCache = $this->cache->getWithSetCallback(
// Group by constraint ID/hash, cat family ID/hash, or something else useful
$this->cache->makeKey( 'cat-situation-tolerability-checks', $groupKey ),
WANObjectCache::TTL_DAY, // rarely used groups should fade away
// The $scenarioKey format is $constraintId:<ID/hash of $situation>
function ( $cacheMap ) use ( $scenarioKey, $constraintId, $situation ) {
$lruCache = MapCacheLRU::newFromArray( $cacheMap ?: [], self::CACHE_SIZE );
$result = $lruCache->get( $scenarioKey ); // triggers LRU bump if present
if ( $result === null || $this->isScenarioResultExpired( $result ) ) {
$result = $this->checkScenarioTolerability( $constraintId, $situation );
$lruCache->set( $scenarioKey, $result, 3 / 8 );
}
// Save the new LRU cache map and reset the map's TTL
return $lruCache->toArray();
},
[
// Once map is > 1 sec old, consider refreshing
'ageNew' => 1,
// Update within 5 seconds after "ageNew" given a 1hz cache check rate
'hotTTR' => 5,
// Avoid querying cache servers multiple times in a request; this also means
// that a request can only alter the value of any given constraint key once
]
);
$tolerability = isset( $catSituationTolerabilityCache[$scenarioKey] )
? $catSituationTolerabilityCache[$scenarioKey]
: $this->checkScenarioTolerability( $constraintId, $situation );
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1991
you have access to all of the normal MediaWiki so you can get a DB use the cache
See also
WANObjectCache::get()
WANObjectCache::set()
Parameters
string$keyCache key made from makeKey() or makeGlobalKey()
int$ttlSeconds to live for key updates. Special values are:
  • WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
  • WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
callable$callbackValue generation function
array$optsOptions map:
  • checkKeys: List of "check" keys. The key at $key will be seen as stale when either touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This is useful if thousands or millions of keys depend on the same entity. The entity can simply have its "check" key updated whenever the entity is modified. Default: [].
  • graceTTL: If the key is invalidated (by "checkKeys"/"touchedCallback") less than this many seconds ago, consider reusing the stale value. The odds of a refresh becomes more likely over time, becoming certain once the grace period is reached. This can reduce traffic spikes when millions of keys are compared to the same "check" key and touchCheckKey() or resetCheckKey() is called on that "check" key. This option is not useful for avoiding traffic spikes in the case of the key simply expiring on account of its TTL (use "lowTTL" instead). Default: WANObjectCache::GRACE_TTL_NONE.
  • lockTSE: If the key is tombstoned or invalidated (by "checkKeys"/"touchedCallback") less than this many seconds ago, try to have a single thread handle cache regeneration at any given time. Other threads will use stale values if possible. If, on miss, the time since expiration is low, the assumption is that the key is hot and that a stampede is worth avoiding. Note that if the key falls out of cache then concurrent threads will all run the callback on cache miss until the value is saved in cache. The only stampede protection in that case is from duplicate cache sets when the callback takes longer than WANObjectCache::SET_DELAY_HIGH_MS milliseconds; consider using "busyValue" if such stampedes are a problem. Note that the higher "lockTSE" is set, the higher the worst-case staleness of returned values can be. Also note that this option does not by itself handle the case of the key simply expiring on account of its TTL, so make sure that "lowTTL" is not disabled when using this option. Avoid combining this option with delete() as it can always cause a stampede due to their being no stale value available until after a thread completes the callback. Use WANObjectCache::TSE_NONE to disable this logic. Default: WANObjectCache::TSE_NONE.
  • busyValue: If no value exists and another thread is currently regenerating it, use this as a fallback value (or a callback to generate such a value). This assures that cache stampedes cannot happen if the value falls out of cache. This can be used as insurance against cache regeneration becoming very slow for some reason (greater than the TTL). Default: null.
  • pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids network I/O when a key is read several times. This will not cache when the callback returns false, however. Note that any purges will not be seen while process cached; since the callback should use replica DBs and they may be lagged or have snapshot isolation anyway, this should not typically matter. Default: WANObjectCache::TTL_UNCACHEABLE.
  • pcGroup: Process cache group to use instead of the primary one. If set, this must be of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing large values, small yet numerous values, or some values with a high cost of eviction. It is generally preferable to use a class constant when setting this value. This has no effect unless pcTTL is used. Default: WANObjectCache::PC_PRIMARY.
  • version: Integer version number. This lets callers make breaking changes to the format of cached values without causing problems for sites that use non-instantaneous code deployments. Old and new code will recognize incompatible versions and purges from both old and new code will been seen by each other. When this method encounters an incompatibly versioned value at the provided key, a "variant key" will be used for reading from and saving to cache. The variant key is specific to the key and version number provided to this method. If the variant key value is older than that of the provided key, or the provided key is non-existant, then the variant key will be seen as non-existant. Therefore, delete() calls invalidate the provided key's variant keys. The "checkKeys" and "touchedCallback" options still apply to variant keys as usual. Avoid storing class objects, as this reduces compatibility (due to serialization). Default: null.
  • minAsOf: Reject values if they were generated before this UNIX timestamp. This is useful if the source of a key is suspected of having possibly changed recently, and the caller wants any such changes to be reflected. Default: WANObjectCache::MIN_TIMESTAMP_NONE.
  • hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old. This uses randomization to avoid triggering cache stampedes. The TTR is useful at reducing the impact of missed cache purges, since the effect of a heavily referenced key being stale is worse than that of a rarely referenced key. Unlike simply lowering $ttl, seldomly used keys are largely unaffected by this option, which makes it possible to have a high hit rate for the "long-tail" of less-used keys. Default: WANObjectCache::HOT_TTR.
  • lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less than this. It becomes more likely over time, becoming certain once the key is expired. This helps avoid cache stampedes that might be triggered due to the key expiring. Default: WANObjectCache::LOW_TTL.
  • ageNew: Consider popularity refreshes only once a key reaches this age in seconds. Default: WANObjectCache::AGE_NEW.
  • staleTTL: Seconds to keep the key around if it is stale. This means that on cache miss the callback may get $oldValue/$oldAsOf values for keys that have already been expired for this specified time. This is useful if adaptiveTTL() is used on the old value's as-of time when it is verified as still being correct. Default: WANObjectCache::STALE_TTL_NONE
  • touchedCallback: A callback that takes the current value and returns a UNIX timestamp indicating the last time a dynamic dependency changed. Null can be returned if there are no relevant dependency changes to check. This can be used to check against things like last-modified times of files or DB timestamp fields. This should generally not be used for small and easily queried values in a DB if the callback itself ends up doing a similarly expensive DB query to check a timestamp. Usages of this option makes the most sense for values that are moderately to highly expensive to regenerate and easy to query for dependency timestamps. The use of "pcTTL" reduces timestamp queries. Default: null.
Returns
mixed Value found or written to the key
Note
Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
Options added in 1.31: staleTTL, graceTTL
Options added in 1.33: touchedCallback
Callable type hints are not used to avoid class-autoloading

Definition at line 1215 of file WANObjectCache.php.

References $value, doGetWithSetCallback(), getProcessCache(), makeGlobalKey(), and use.

Referenced by getMultiWithSetCallback(), getMultiWithUnionSetCallback(), WANObjectCacheTest\testBusyValue(), WANObjectCacheTest\testGetWithSetCallback(), WANObjectCacheTest\testGetWithSetcallback_touched(), WANObjectCacheTest\testGetWithSetCallback_versions(), WANObjectCacheTest\testInterimHoldOffCaching(), WANObjectCacheTest\testLockTSE(), WANObjectCacheTest\testLockTSESlow(), and WANObjectCacheTest\testPreemtiveRefresh().

◆ isAliveOrInGracePeriod()

WANObjectCache::isAliveOrInGracePeriod (   $curTTL,
  $graceTTL 
)
protected

Check if a key is fresh or in the grace window and thus due for randomized reuse.

If $curTTL > 0 (e.g. not expired) this returns true. Otherwise, the chance of returning true decrease steadily from 100% to 0% as the |$curTTL| moves from 0 to $graceTTL seconds. This handles widely varying levels of cache access traffic.

If $curTTL <= -$graceTTL (e.g. already expired), then this returns false.

Parameters
float$curTTLApproximate TTL left on the key if present
int$graceTTLConsider using stale values if $curTTL is greater than this
Returns
bool

Definition at line 2140 of file WANObjectCache.php.

References worthRefreshExpiring().

Referenced by doGetWithSetCallback().

◆ isValid()

WANObjectCache::isValid (   $value,
  $versioned,
  $asOf,
  $minTime,
  $purgeTime = null 
)
protected

Check if $value is not false, versioned (if needed), and not older than $minTime (if set)

Parameters
array | bool$value
bool$versioned
float$asOfThe time $value was generated
float$minTimeThe last time the main value was generated (0.0 if unknown)
float | null$purgeTimeThe last time the value was invalidated
Returns
bool

Definition at line 2235 of file WANObjectCache.php.

References $value.

Referenced by doGetWithSetCallback(), and getInterimValue().

◆ isVolatileValueAgeNegligible()

WANObjectCache::isVolatileValueAgeNegligible (   $age)
private
Parameters
float$ageAge of volatile/interim key in seconds
Returns
bool Whether the age of a volatile value is negligible

Definition at line 1458 of file WANObjectCache.php.

Referenced by doGetWithSetCallback().

◆ makeGlobalKey()

WANObjectCache::makeGlobalKey (   $class,
  $component = null 
)
See also
BagOStuff::makeGlobalKey()
Parameters
string$classKey class
string | null$component[optional] Key component (starting with a key collection name)
Returns
string Colon-delimited list of $keyspace followed by escaped components of $args
Since
1.27

Definition at line 1884 of file WANObjectCache.php.

References cache.

Referenced by getWithSetCallback(), and WANObjectCacheTest\testEpoch().

◆ makeKey()

WANObjectCache::makeKey (   $class,
  $component = null 
)
See also
BagOStuff::makeKey()
Parameters
string$classKey class
string | null$component[optional] Key component (starting with a key collection name)
Returns
string Colon-delimited list of $keyspace followed by escaped components of $args
Since
1.27

Definition at line 1873 of file WANObjectCache.php.

References cache.

Referenced by WANObjectCacheTest\testGetWithSetCallback().

◆ makeMultiKeys()

WANObjectCache::makeMultiKeys ( array  $entities,
callable  $keyFunc 
)
final
Parameters
array$entitiesList of entity IDs
callable$keyFuncCallback yielding a key from (entity ID, this WANObjectCache)
Returns
ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
Since
1.28

Definition at line 1894 of file WANObjectCache.php.

References as.

Referenced by WANObjectCacheTest\testGetMultiWithSetCallback(), and WANObjectCacheTest\testGetMultiWithUnionSetCallback().

◆ makePurgeValue()

WANObjectCache::makePurgeValue (   $timestamp,
  $holdoff 
)
protected
Parameters
float$timestamp
int$holdoffIn seconds
Returns
string Wrapped purge value

Definition at line 2371 of file WANObjectCache.php.

Referenced by getMultiCheckKeyTime(), processCheckKeys(), and relayPurge().

◆ newEmpty()

static WANObjectCache::newEmpty ( )
static

Get an instance that wraps EmptyBagOStuff.

Returns
WANObjectCache

Definition at line 278 of file WANObjectCache.php.

◆ parsePurgeValue()

WANObjectCache::parsePurgeValue (   $value)
protected
Parameters
string | array | bool$valuePossible string of the form "PURGED:<timestamp>:<holdoff>"
Returns
array|bool Array containing a UNIX timestamp (float) and holdoff period (integer), or false if value isn't a valid purge value

Definition at line 2338 of file WANObjectCache.php.

References $value.

Referenced by getMultiCheckKeyTime(), processCheckKeys(), reapCheckKey(), and unwrap().

◆ prefixCacheKeys()

static WANObjectCache::prefixCacheKeys ( array  $keys,
  $prefix 
)
staticprotected
Parameters
array$keys
string$prefix
Returns
string[]

Definition at line 2314 of file WANObjectCache.php.

References $keys, $res, and as.

◆ processCheckKeys()

WANObjectCache::processCheckKeys ( array  $timeKeys,
array  $wrappedValues,
  $now 
)
private
Since
1.27
Parameters
array$timeKeysList of prefixed time check keys
array$wrappedValues
float$now
Returns
array List of purge value arrays

Definition at line 469 of file WANObjectCache.php.

References as, cache, makePurgeValue(), and parsePurgeValue().

Referenced by getMulti().

◆ reap()

WANObjectCache::reap (   $key,
  $purgeTimestamp,
$isStale = false 
)
final

Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp.

This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids broadcasting in mcrouter setups and also avoids races with new tombstones.

Parameters
string$keyCache key
int$purgeTimestampUNIX timestamp of purge
bool&$isStaleWhether the key is stale
Returns
bool Success
Since
1.28

Definition at line 1819 of file WANObjectCache.php.

References cache.

◆ reapCheckKey()

WANObjectCache::reapCheckKey (   $key,
  $purgeTimestamp,
$isStale = false 
)
final

Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp.

Parameters
string$keyCache key
int$purgeTimestampUNIX timestamp of purge
bool&$isStaleWhether the key is stale
Returns
bool Success
Since
1.28

Definition at line 1848 of file WANObjectCache.php.

References cache, and parsePurgeValue().

◆ relayDelete()

WANObjectCache::relayDelete (   $key)
protected

Do the actual async bus delete of a key.

Parameters
string$keyCache key
Returns
bool Success

Definition at line 2092 of file WANObjectCache.php.

References cache.

Referenced by delete(), and resetCheckKey().

◆ relayPurge()

WANObjectCache::relayPurge (   $key,
  $ttl,
  $holdoff 
)
protected

Do the actual async bus purge of a key.

This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"

Parameters
string$keyCache key
int$ttlHow long to keep the tombstone [seconds]
int$holdoffHOLDOFF_* constant controlling how long to ignore sets for this key
Returns
bool Success

Definition at line 2065 of file WANObjectCache.php.

References cache, getCurrentTime(), and makePurgeValue().

Referenced by delete(), and touchCheckKey().

◆ resetCheckKey()

WANObjectCache::resetCheckKey (   $key)
final

Delete a "check" key from all datacenters, invalidating keys that use it.

This is similar to touchCheckKey() in that keys using it via get(), getMulti(), or getWithSetCallback() will be invalidated. The differences are:

  • a) The "check" key will be deleted from all caches and lazily re-initialized when accessed (rather than set everywhere)
  • b) Thus, dependent keys will be known to be stale, but not for how long (they are treated as "just" purged), which effects any lockTSE logic in getWithSetCallback()
  • c) Since "check" keys are initialized only on the server the key hashes to, any temporary ejection of that server will cause the value to be seen as purged as a new server will initialize the "check" key.

The advantage here is that the "check" keys, which have high TTLs, will only be created when a get*() method actually uses that key. This is better when a large number of "check" keys are invalided in a short period of time.

Note that "check" keys won't collide with other regular keys.

See also
WANObjectCache::get()
WANObjectCache::getWithSetCallback()
WANObjectCache::touchCheckKey()
Parameters
string$keyCache key
Returns
bool True if the item was purged or not found, false on failure

Definition at line 904 of file WANObjectCache.php.

References determineKeyClassForStats(), and relayDelete().

Referenced by WANObjectCacheTest\testTouchKeys().

◆ resolveCTL()

WANObjectCache::resolveCTL (   $value,
  $curTTL,
  $curInfo,
  $touchedCallback 
)
protected
Parameters
mixed$value
float | null$curTTL
array$curInfo
callable | null$touchedCallback
Returns
array (current time left or null, UNIX timestamp of last purge or null)
Note
Callable type hints are not used to avoid class-autoloading

Definition at line 1505 of file WANObjectCache.php.

References $value.

Referenced by doGetWithSetCallback().

◆ resolveTouched()

WANObjectCache::resolveTouched (   $value,
  $lastPurge,
  $touchedCallback 
)
protected
Parameters
mixed$value
float | null$lastPurge
callable | null$touchedCallback
Returns
float|null UNIX timestamp of last purge or null
Note
Callable type hints are not used to avoid class-autoloading

Definition at line 1529 of file WANObjectCache.php.

References $value.

Referenced by doGetWithSetCallback().

◆ scheduleAsyncRefresh()

WANObjectCache::scheduleAsyncRefresh (   $key,
  $ttl,
  $callback,
  $opts 
)
private
Parameters
string$key
int$ttl
callable$callback
array$opts
Returns
bool Success

Definition at line 2112 of file WANObjectCache.php.

References doGetWithSetCallback(), and use.

Referenced by doGetWithSetCallback().

◆ set()

WANObjectCache::set (   $key,
  $value,
  $ttl = self::TTL_INDEFINITE,
array  $opts = [] 
)
final

Set the value of a key in cache.

Simply calling this method when source data changes is not valid because the changes do not replicate to the other WAN sites. In that case, delete() should be used instead. This method is intended for use on cache misses.

If the data was read from a snapshot-isolated transactions (e.g. the default REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:

  • a) T1 starts
  • b) T2 updates a row, calls delete(), and commits
  • c) The HOLDOFF_TTL passes, expiring the delete() tombstone
  • d) T1 reads the row and calls set() due to a cache miss
  • e) Stale value is stuck in cache

Setting 'lag' and 'since' help avoids keys getting stuck in stale states.

Be aware that this does not update the process cache for getWithSetCallback() callers. Keys accessed via that method are not generally meant to also be set using this primitive method.

Do not use this method on versioned keys accessed via getWithSetCallback().

Example usage:

$setOpts = Database::getCacheSetOptions( $dbr );
// Fetch the row from the DB
$row = $dbr->selectRow( ... );
$key = $cache->makeKey( 'building', $buildingId );
$cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
Parameters
string$keyCache key
mixed$value
int$ttlSeconds to live. Special values are:
  • WANObjectCache::TTL_INDEFINITE: Cache forever (default)
array$optsOptions map:
  • lag: seconds of replica DB lag. Typically, this is either the replica DB lag before the data was read or, if applicable, the replica DB lag before the snapshot-isolated transaction the data was read from started. Use false to indicate that replication is not running. Default: 0 seconds
  • since: UNIX timestamp of the data in $value. Typically, this is either the current time the data was read or (if applicable) the time when the snapshot-isolated transaction the data was read from started. Default: 0 seconds
  • pending: whether this data is possibly from an uncommitted write transaction. Generally, other threads should not see values from the future and they certainly should not see ones that ended up getting rolled back. Default: false
  • lockTSE: if excessive replication/snapshot lag is detected, then store the value with this TTL and flag it as stale. This is only useful if the reads for this key use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set then it will still add on to this TTL in the excessive lag scenario. Default: WANObjectCache::TSE_NONE
  • staleTTL: seconds to keep the key around if it is stale. The get()/getMulti() methods return such stale values with a $curTTL of 0, and getWithSetCallback() will call the regeneration callback in such cases, passing in the old value and its as-of time to the callback. This is useful if adaptiveTTL() is used on the old value's as-of time when it is verified as still being correct. Default: WANObjectCache::STALE_TTL_NONE.
  • creating: optimize for the case where the key does not already exist. Default: false
Note
Options added in 1.28: staleTTL
Options added in 1.33: creating
Returns
bool Success

Definition at line 554 of file WANObjectCache.php.

References $cache, $value, cache, false, getCurrentTime(), use, and wrap().

Referenced by JobQueueDB\doDeduplicateRootJob(), MessageBlobStore\recacheMessageBlob(), WANObjectCacheTest\testCheckKeyInitHoldoff(), WANObjectCacheTest\testEpoch(), WANObjectCacheTest\testGetMulti(), and WANObjectCacheTest\testGetMultiCheckKeys().

◆ setInterimValue()

WANObjectCache::setInterimValue (   $key,
  $value,
  $tempTTL,
  $newAsOf 
)
protected
Parameters
string$key
mixed$value
int$tempTTL
float$newAsOf

Definition at line 1568 of file WANObjectCache.php.

References $value, cache, use, and wrap().

Referenced by doGetWithSetCallback().

◆ setLogger()

WANObjectCache::setLogger ( LoggerInterface  $logger)
Parameters
LoggerInterface$logger

Definition at line 269 of file WANObjectCache.php.

Referenced by __construct().

◆ setMockTime()

◆ touchCheckKey()

WANObjectCache::touchCheckKey (   $key,
  $holdoff = self::HOLDOFF_TTL 
)
final

Purge a "check" key from all datacenters, invalidating keys that use it.

This should only be called when the underlying data (being cached) changes in a significant way, and it is impractical to call delete() on all keys that should be changed. When get() is called on those keys, the relevant "check" keys must be supplied for this to work.

The "check" key essentially represents a last-modified time of an entity. When the key is touched, the timestamp will be updated to the current time. Keys using the "check" key via get(), getMulti(), or getWithSetCallback() will be invalidated. This approach is useful if many keys depend on a single entity.

The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the future by get*() methods in order to avoid race conditions where keys are updated with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check" key, making it possible to know the timestamp of the last change to the corresponding entities in most cases. This might use more cache space than resetCheckKey().

When a few important keys get a large number of hits, a high cache time is usually desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate in such cases since the "time since expiry" cannot be inferred, causing any get() after the reset to treat the key as being "hot", resulting in more stale value usage.

Note that "check" keys won't collide with other regular keys.

See also
WANObjectCache::get()
WANObjectCache::getWithSetCallback()
WANObjectCache::resetCheckKey()
Parameters
string$keyCache key
int$holdoffHOLDOFF_TTL or HOLDOFF_NONE constant
Returns
bool True if the item was purged or not found, false on failure

Definition at line 867 of file WANObjectCache.php.

References determineKeyClassForStats(), and relayPurge().

Referenced by MessageBlobStore\clear(), WANObjectCacheTest\testEpoch(), WANObjectCacheTest\testGetMultiCheckKeys(), WANObjectCacheTest\testGetWithSetCallback(), and WANObjectCacheTest\testTouchKeys().

◆ unwrap()

WANObjectCache::unwrap (   $wrapped,
  $now 
)
protected

Do not use this method outside WANObjectCache.

The cached value will be false if absent/tombstoned/malformed

Parameters
array | string | bool$wrapped
float$nowUnix Current timestamp (preferrably pre-query)
Returns
array (cached value or false, current TTL, value timestamp, tombstone timestamp)

Definition at line 2276 of file WANObjectCache.php.

References null, and parsePurgeValue().

Referenced by getInterimValue(), and getMulti().

◆ useInterimHoldOffCaching()

WANObjectCache::useInterimHoldOffCaching (   $enabled)
final

Enable or disable the use of brief caching for tombstoned keys.

When a key is purged via delete(), there normally is a period where caching is hold-off limited to an extremely short time. This method will disable that caching, forcing the callback to run for any of:

  • WANObjectCache::getWithSetCallback()
  • WANObjectCache::getMultiWithSetCallback()
  • WANObjectCache::getMultiWithUnionSetCallback()

This is useful when both:

  • a) the database used by the callback is known to be up-to-date enough for some particular purpose (e.g. replica DB has applied transaction X)
  • b) the caller needs to exploit that fact, and therefore needs to avoid the use of inherently volatile and possibly stale interim keys
See also
WANObjectCache::delete()
Parameters
bool$enabledWhether to enable interim caching
Since
1.31

Definition at line 1957 of file WANObjectCache.php.

References useInterimHoldOffCaching().

Referenced by getInterimValue(), WANObjectCacheTest\testInterimHoldOffCaching(), and useInterimHoldOffCaching().

◆ worthRefreshExpiring()

WANObjectCache::worthRefreshExpiring (   $curTTL,
  $lowTTL 
)
protected

Check if a key is nearing expiration and thus due for randomized regeneration.

This returns false if $curTTL >= $lowTTL. Otherwise, the chance of returning true increases steadily from 0% to 100% as the $curTTL moves from $lowTTL to 0 seconds. This handles widely varying levels of cache access traffic.

If $curTTL <= 0 (e.g. already expired), then this returns false.

Parameters
float$curTTLApproximate TTL left on the key if present
float$lowTTLConsider a refresh when $curTTL is less than this
Returns
bool

Reimplemented in NearExpiringWANObjectCache.

Definition at line 2170 of file WANObjectCache.php.

Referenced by doGetWithSetCallback(), and isAliveOrInGracePeriod().

◆ worthRefreshPopular()

WANObjectCache::worthRefreshPopular (   $asOf,
  $ageNew,
  $timeTillRefresh,
  $now 
)
protected

Check if a key is due for randomized regeneration due to its popularity.

This is used so that popular keys can preemptively refresh themselves for higher consistency (especially in the case of purge loss/delay). Unpopular keys can remain in cache with their high nominal TTL. This means popular keys keep good consistency, whether the data changes frequently or not, and long-tail keys get to stay in cache and get hits too. Similar to worthRefreshExpiring(), randomization is used.

Parameters
float$asOfUNIX timestamp of the value
int$ageNewAge of key when this might recommend refreshing (seconds)
int$timeTillRefreshAge of key when it should be refreshed if popular (seconds)
float$nowThe current UNIX timestamp
Returns
bool

Reimplemented in PopularityRefreshingWANObjectCache.

Definition at line 2199 of file WANObjectCache.php.

Referenced by doGetWithSetCallback().

◆ wrap()

WANObjectCache::wrap (   $value,
  $ttl,
  $now 
)
protected

Do not use this method outside WANObjectCache.

Parameters
mixed$value
int$ttl[0=forever]
float$nowUnix Current timestamp just before calling set()
Returns
array

Definition at line 2258 of file WANObjectCache.php.

References $value.

Referenced by set(), and setInterimValue().

Member Data Documentation

◆ $asyncHandler

callable null WANObjectCache::$asyncHandler
protected

Function that takes a WAN cache callback and runs it later.

Definition at line 134 of file WANObjectCache.php.

◆ $cache

BagOStuff WANObjectCache::$cache
protected

The local datacenter cache.

Definition at line 118 of file WANObjectCache.php.

◆ $callbackDepth

int WANObjectCache::$callbackDepth = 0
private

Callback stack depth for getWithSetCallback()

Definition at line 139 of file WANObjectCache.php.

◆ $cluster

string WANObjectCache::$cluster
protected

Cache cluster name for mcrouter use.

Definition at line 126 of file WANObjectCache.php.

◆ $epoch

float WANObjectCache::$epoch
protected

Unix timestamp of the oldest possible valid values.

Definition at line 136 of file WANObjectCache.php.

◆ $logger

LoggerInterface WANObjectCache::$logger
protected

Definition at line 128 of file WANObjectCache.php.

◆ $mcrouterAware

WANObjectCache::$mcrouterAware
protected

@bar bool Whether to use mcrouter key prefixing for routing

Definition at line 122 of file WANObjectCache.php.

◆ $processCaches

MapCacheLRU [] WANObjectCache::$processCaches = []
protected

Map of group PHP instance caches.

Definition at line 120 of file WANObjectCache.php.

◆ $region

string WANObjectCache::$region
protected

Physical region for mcrouter use.

Definition at line 124 of file WANObjectCache.php.

◆ $stats

StatsdDataFactoryInterface WANObjectCache::$stats
protected

Definition at line 130 of file WANObjectCache.php.

◆ $useInterimHoldOffCaching

bool WANObjectCache::$useInterimHoldOffCaching = true
protected

Whether to use "interim" caching while keys are tombstoned.

Definition at line 132 of file WANObjectCache.php.

◆ $wallClockOverride

float null WANObjectCache::$wallClockOverride
private

Definition at line 146 of file WANObjectCache.php.

◆ $warmupCache

mixed [] WANObjectCache::$warmupCache = []
private

Temporary warm-up cache.

Definition at line 141 of file WANObjectCache.php.

Referenced by getRawKeysForWarmup().

◆ $warmupKeyMisses

int WANObjectCache::$warmupKeyMisses = 0
private

Key fetched.

Definition at line 143 of file WANObjectCache.php.

◆ AGE_NEW

const WANObjectCache::AGE_NEW = 60

Never consider performing "popularity" refreshes until a key reaches this age.

Definition at line 168 of file WANObjectCache.php.

◆ CHECK_KEY_TTL

const WANObjectCache::CHECK_KEY_TTL = self::TTL_YEAR

Seconds to keep dependency purge keys around.

Definition at line 156 of file WANObjectCache.php.

◆ COOLOFF_KEY_PREFIX

const WANObjectCache::COOLOFF_KEY_PREFIX = 'WANCache:c:'

Definition at line 221 of file WANObjectCache.php.

◆ COOLOFF_TTL

const WANObjectCache::COOLOFF_TTL = 1

Seconds to no-op key set() calls to avoid large blob I/O stampedes.

Definition at line 163 of file WANObjectCache.php.

◆ FLD_FLAGS

const WANObjectCache::FLD_FLAGS = 4

Definition at line 214 of file WANObjectCache.php.

◆ FLD_HOLDOFF

const WANObjectCache::FLD_HOLDOFF = 5

Definition at line 215 of file WANObjectCache.php.

◆ FLD_TIME

const WANObjectCache::FLD_TIME = 3

Definition at line 213 of file WANObjectCache.php.

◆ FLD_TTL

const WANObjectCache::FLD_TTL = 2

Definition at line 212 of file WANObjectCache.php.

◆ FLD_VALUE

const WANObjectCache::FLD_VALUE = 1

Definition at line 211 of file WANObjectCache.php.

◆ FLD_VERSION

const WANObjectCache::FLD_VERSION = 0

Definition at line 210 of file WANObjectCache.php.

◆ GRACE_TTL_NONE

const WANObjectCache::GRACE_TTL_NONE = 0

Idiom for set()/getWithSetCallback() for "no post-expired grace period".

Definition at line 187 of file WANObjectCache.php.

◆ HIT_RATE_HIGH

const WANObjectCache::HIT_RATE_HIGH = 1

Hits/second for a refresh to be expected within the "popularity" window.

Definition at line 172 of file WANObjectCache.php.

◆ HOLDOFF_NONE

const WANObjectCache::HOLDOFF_NONE = 0

Idiom for delete() for "no hold-off".

Definition at line 183 of file WANObjectCache.php.

◆ HOLDOFF_TTL

const WANObjectCache::HOLDOFF_TTL = 11

Seconds to tombstone keys on delete()

Definition at line 153 of file WANObjectCache.php.

◆ HOT_TTR

const WANObjectCache::HOT_TTR = 900

The time length of the "popularity" refresh window for hot keys.

Definition at line 170 of file WANObjectCache.php.

◆ INTERIM_KEY_PREFIX

const WANObjectCache::INTERIM_KEY_PREFIX = 'WANCache:i:'

Definition at line 218 of file WANObjectCache.php.

◆ INTERIM_KEY_TTL

const WANObjectCache::INTERIM_KEY_TTL = 1

Seconds to keep interim value keys for tombstoned keys around.

Definition at line 158 of file WANObjectCache.php.

◆ LOCK_TTL

const WANObjectCache::LOCK_TTL = 10

Seconds to keep lock keys around.

Definition at line 161 of file WANObjectCache.php.

◆ LOW_TTL

const WANObjectCache::LOW_TTL = 30

Default remaining TTL at which to consider pre-emptive regeneration.

Definition at line 165 of file WANObjectCache.php.

◆ MAX_COMMIT_DELAY

const WANObjectCache::MAX_COMMIT_DELAY = 3

Max time expected to pass between delete() and DB commit finishing.

Definition at line 149 of file WANObjectCache.php.

◆ MAX_READ_LAG

const WANObjectCache::MAX_READ_LAG = 7

Max replication+snapshot lag before applying TTL_LAGGED or disallowing set()

Definition at line 151 of file WANObjectCache.php.

◆ MIN_TIMESTAMP_NONE

const WANObjectCache::MIN_TIMESTAMP_NONE = 0.0

Idiom for getWithSetCallback() for "no minimum required as-of timestamp".

Definition at line 190 of file WANObjectCache.php.

◆ MUTEX_KEY_PREFIX

const WANObjectCache::MUTEX_KEY_PREFIX = 'WANCache:m:'

Definition at line 220 of file WANObjectCache.php.

◆ PASS_BY_REF

const WANObjectCache::PASS_BY_REF = -1

Parameter to get()/getMulti() to return extra information by reference.

Definition at line 205 of file WANObjectCache.php.

◆ PC_PRIMARY

const WANObjectCache::PC_PRIMARY = 'primary:1000'

Definition at line 228 of file WANObjectCache.php.

◆ PURGE_VAL_PREFIX

const WANObjectCache::PURGE_VAL_PREFIX = 'PURGED:'

Definition at line 223 of file WANObjectCache.php.

◆ RAMPUP_TTL

const WANObjectCache::RAMPUP_TTL = 30

Seconds to ramp up to the "popularity" refresh chance after a key is no longer new.

Definition at line 174 of file WANObjectCache.php.

◆ RECENT_SET_HIGH_MS

const WANObjectCache::RECENT_SET_HIGH_MS = 100

Max millisecond set() backoff for keys in hold-off (far less than INTERIM_KEY_TTL)

Definition at line 202 of file WANObjectCache.php.

◆ RECENT_SET_LOW_MS

const WANObjectCache::RECENT_SET_LOW_MS = 50

Min millisecond set() backoff for keys in hold-off (far less than INTERIM_KEY_TTL)

Definition at line 200 of file WANObjectCache.php.

◆ SET_DELAY_HIGH_MS

const WANObjectCache::SET_DELAY_HIGH_MS = 50

Milliseconds of delay after get() where set() storms are a consideration with 'lockTSE'.

Definition at line 198 of file WANObjectCache.php.

◆ STALE_TTL_NONE

const WANObjectCache::STALE_TTL_NONE = 0

Idiom for set()/getWithSetCallback() for "do not augment the storage medium TTL".

Definition at line 185 of file WANObjectCache.php.

◆ TIME_KEY_PREFIX

const WANObjectCache::TIME_KEY_PREFIX = 'WANCache:t:'

Definition at line 219 of file WANObjectCache.php.

◆ TINY_NEGATIVE

const WANObjectCache::TINY_NEGATIVE = -0.000001

Tiny negative float to use when CTL comes up >= 0 due to clock skew.

Definition at line 193 of file WANObjectCache.php.

◆ TINY_POSTIVE

const WANObjectCache::TINY_POSTIVE = 0.000001

Tiny positive float to use when using "minTime" to assert an inequality.

Definition at line 195 of file WANObjectCache.php.

◆ TSE_NONE

const WANObjectCache::TSE_NONE = -1

Idiom for getWithSetCallback() callbacks to 'lockTSE' logic.

Definition at line 179 of file WANObjectCache.php.

◆ TTL_LAGGED

const WANObjectCache::TTL_LAGGED = 30

Max TTL to store keys when a data sourced is lagged.

Definition at line 181 of file WANObjectCache.php.

◆ TTL_UNCACHEABLE

const WANObjectCache::TTL_UNCACHEABLE = -1

Idiom for getWithSetCallback() callbacks to avoid calling set()

Definition at line 177 of file WANObjectCache.php.

◆ VALUE_KEY_PREFIX

const WANObjectCache::VALUE_KEY_PREFIX = 'WANCache:v:'

Definition at line 217 of file WANObjectCache.php.

◆ VERSION

const WANObjectCache::VERSION = 1

Cache format version number.

Definition at line 208 of file WANObjectCache.php.

◆ VFLD_DATA

const WANObjectCache::VFLD_DATA = 'WOC:d'

Definition at line 225 of file WANObjectCache.php.

◆ VFLD_VERSION

const WANObjectCache::VFLD_VERSION = 'WOC:v'

Definition at line 226 of file WANObjectCache.php.


The documentation for this class was generated from the following file: