MediaWiki REL1_35
|
Multi-datacenter aware caching interface. More...
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=[], array $cbParams=[]) | |
Method to fetch/regenerate a cache key. | |
hash256 ( $component) | |
Hash a possibly long string into a suitable component for makeKey()/makeGlobalKey() | |
makeGlobalKey ( $class,... $components) | |
makeKey ( $class,... $components) | |
makeMultiKeys (array $ids, $keyCallback) | |
Get an iterator of (cache key => entity ID) for a list of entity IDs. | |
multiRemap (array $ids, array $res) | |
Get an (ID => value) map from (i) a non-unique list of entity IDs, and (ii) the list of corresponding entity values by first appearance of each ID in the entity ID list. | |
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. | |
Protected Member Functions | |
getCurrentTime () | |
isValid ( $value, $asOf, $minAsOf, $purgeTime=null) | |
Check if $value is not false, versioned (if needed), and not older than $minTime (if set) | |
relayDelete ( $key) | |
Do the actual async bus delete of a key. | |
relayPurge ( $key, $ttl, $holdoff) | |
Do the actual async bus purge of a key. | |
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. | |
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. | |
string bool | $coalesceKeys |
Whether "sister" keys should be coalesced to the same cache server. | |
int | $coalesceScheme |
Scheme to use for key coalescing (Hash Tags or Hash Stops) | |
float | $epoch |
Unix timestamp of the oldest possible valid values. | |
LoggerInterface | $logger |
bool | $mcrouterAware |
Whether to use mcrouter key prefixing for routing. | |
MapCacheLRU[] | $processCaches = [] |
Map of group PHP instance caches. | |
string | $region |
Physical region for mcrouter use. | |
string | $secret |
Stable secret used for hasing long strings into key components. | |
StatsdDataFactoryInterface | $stats |
bool | $useInterimHoldOffCaching = true |
Whether to use "interim" caching while keys are tombstoned. | |
Private Member Functions | |
checkAndSetCooloff ( $key, $kClass, $value, $elapsed, $hasLock) | |
Check whether set() is rate-limited to avoid concurrent I/O spikes. | |
claimStampedeLock ( $key) | |
determineKeyClassForStats ( $key) | |
fetchOrRegenerate ( $key, $ttl, $callback, array $opts, array $cbParams) | |
Do the actual I/O for getWithSetCallback() when needed. | |
getInterimValue ( $key, $minAsOf) | |
getNonProcessCachedMultiKeys (ArrayIterator $keys, array $opts) | |
getProcessCache ( $group) | |
getProcessCacheKey ( $key, $version) | |
getRawKeysForWarmup (array $keys, array $checkKeys) | |
isAliveOrInGracePeriod ( $curTTL, $graceTTL) | |
Check if a key is fresh or in the grace window and thus due for randomized reuse. | |
isVolatileValueAgeNegligible ( $age) | |
makePurgeValue ( $timestamp, $holdoff) | |
makeSisterKey ( $baseKey, $typeChar) | |
Get a cache key that should be collocated with a base key. | |
makeSisterKeys (array $baseKeys, $type) | |
Get cache keys that should be collocated with their corresponding base keys. | |
parsePurgeValue ( $value) | |
processCheckKeys (array $timeKeys, array $wrappedValues, $now) | |
resolveBusyValue ( $busyValue) | |
resolveCTL ( $value, $curTTL, $curInfo, $touchedCallback) | |
resolveTouched ( $value, $lastPurge, $touchedCallback) | |
scheduleAsyncRefresh ( $key, $ttl, $callback, array $opts, array $cbParams) | |
Schedule a deferred cache regeneration if possible. | |
setInterimValue ( $key, $value, $ttl, $version, $walltime) | |
unwrap ( $wrapped, $now) | |
wrap ( $value, $ttl, $version, $now, $walltime) | |
yieldStampedeLock ( $key, $hasLock) | |
Private Attributes | |
int | $callbackDepth = 0 |
Callback stack depth for getWithSetCallback() | |
int | $keyHighQps |
Reads/second assumed during a hypothetical cache write stampede for a key. | |
float | $keyHighUplinkBps |
Max tolerable bytes/second to spend on a cache write stampede for a key. | |
float null | $wallClockOverride |
mixed[] | $warmupCache = [] |
Temporary warm-up cache. | |
int | $warmupKeyMisses = 0 |
Key fetched. | |
Static Private Attributes | |
static int | $CHECK_KEY_TTL = self::TTL_YEAR |
Seconds to keep dependency purge keys around. | |
static int | $COOLOFF_TTL = 1 |
Seconds to no-op key set() calls to avoid large blob I/O stampedes. | |
static int | $FLD_FLAGS = 4 |
@noinspection PhpUnusedPrivateFieldInspection | |
static int | $FLD_FORMAT_VERSION = 0 |
Key to WAN cache version number. | |
static int | $FLD_GENERATION_TIME = 6 |
Key to how long it took to generate the value. | |
static int | $FLD_TIME = 3 |
Key to the cache timestamp. | |
static int | $FLD_TTL = 2 |
Key to the original TTL. | |
static int | $FLD_VALUE = 1 |
Key to the cached value. | |
static int | $FLD_VALUE_VERSION = 5 |
Key to collection cache version number. | |
static int | $GENERATION_SLOW_SEC = 3 |
Consider value generation slow if it takes more than this many seconds. | |
static int | $INTERIM_KEY_TTL = 1 |
Seconds to keep interim value keys for tombstoned keys around. | |
static int | $LOCK_TTL = 10 |
Seconds to keep lock keys around. | |
static int | $PURGE_HOLDOFF = 1 |
Key to the tombstone entry hold-off TTL. | |
static int | $PURGE_TIME = 0 |
Key to the tombstone entry timestamp. | |
static string | $PURGE_VAL_PREFIX = 'PURGED:' |
Prefix for tombstone key values. | |
static int | $RAMPUP_TTL = 30 |
Seconds to ramp up the chance of regeneration due to expected time-till-refresh. | |
static int | $RECENT_SET_HIGH_MS = 100 |
Max millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL) | |
static int | $RECENT_SET_LOW_MS = 50 |
Min millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL) | |
static float | $TINY_NEGATIVE = -0.000001 |
Tiny negative float to use when CTL comes up >= 0 due to clock skew. | |
static float | $TINY_POSTIVE = 0.000001 |
Tiny positive float to use when using "minTime" to assert an inequality. | |
static string | $TYPE_COOLOFF = 'c' |
Single character cool-off key component. | |
static string | $TYPE_INTERIM = 'i' |
Single character interium key component. | |
static string | $TYPE_MUTEX = 'm' |
Single character mutex key component. | |
static string | $TYPE_TIMESTAMP = 't' |
Single character timestamp key component. | |
static string | $TYPE_VALUE = 'v' |
Single character value mutex key component. | |
static int | $VERSION = 1 |
Cache format version number. | |
Multi-datacenter aware caching interface.
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:
The purge strategy refers to 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.
There are two supported ways to set up broadcasted operations:
true
. Configure mcrouter as follows: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. For any given key that a caller uses, there are several "sister" keys that might be involved under the hood. Each "sister" key differs only by a single-character:
Definition at line 120 of file WANObjectCache.php.
WANObjectCache::__construct | ( | array | $params | ) |
array | $params |
|
Definition at line 310 of file WANObjectCache.php.
References setLogger().
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:
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:
int | float | string | null | $mtime | UNIX timestamp; null if none |
int | $maxTTL | Maximum TTL (seconds) |
int | $minTTL | Minimum TTL (seconds); Default: 30 |
float | $factor | Value in the range (0,1); Default: .2 |
Definition at line 2402 of file WANObjectCache.php.
References getCurrentTime().
|
private |
Check whether set() is rate-limited to avoid concurrent I/O spikes.
This mitigates problems caused by popular keys suddenly becoming unavailable due to unexpected evictions or cache server outages. These cases are not handled by the usual preemptive refresh logic.
With a typical scale-out infrastructure, CPU and query load from getWithSetCallback() invocations is distributed among appservers and replica DBs, but cache operations for a given key route to a single cache server (e.g. striped consistent hashing). A set() stampede to a key can saturate the network link to its cache server. The intensity of the problem is proportionate to the value size and access rate. The duration of the problem is proportionate to value regeneration time.
string | $key | |
string | $kClass | |
mixed | $value | The regenerated value |
float | $elapsed | Seconds spent fetching, validating, and regenerating the value |
bool | $hasLock | Whether this thread has an exclusive regeneration lock |
Definition at line 1683 of file WANObjectCache.php.
References makeSisterKey().
Referenced by fetchOrRegenerate().
|
private |
string | $key |
Definition at line 1585 of file WANObjectCache.php.
References makeSisterKey().
Referenced by fetchOrRegenerate().
|
final |
Clear the "last error" registry.
Definition at line 2293 of file WANObjectCache.php.
WANObjectCache::clearProcessCache | ( | ) |
Clear the in-process caches; useful for testing.
Definition at line 2302 of file WANObjectCache.php.
|
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:
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:
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:
Example usage:
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_TTL_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.
string | $key | Cache key |
int | $ttl | Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL |
Definition at line 830 of file WANObjectCache.php.
References determineKeyClassForStats(), makeSisterKey(), relayDelete(), and relayPurge().
|
private |
string | $key | String of the format <scope>:<class>[:<class or variable>]... |
Definition at line 2713 of file WANObjectCache.php.
Referenced by delete(), fetchOrRegenerate(), resetCheckKey(), and touchCheckKey().
|
private |
Do the actual I/O for getWithSetCallback() when needed.
string | $key | |
int | $ttl | |
callable | $callback | |
array | $opts | |
array | $cbParams |
Definition at line 1416 of file WANObjectCache.php.
References checkAndSetCooloff(), claimStampedeLock(), determineKeyClassForStats(), getCurrentTime(), getInterimValue(), isAliveOrInGracePeriod(), isValid(), isVolatileValueAgeNegligible(), resolveBusyValue(), resolveCTL(), resolveTouched(), scheduleAsyncRefresh(), setInterimValue(), worthRefreshExpiring(), worthRefreshPopular(), and yieldStampedeLock().
Referenced by getWithSetCallback(), and scheduleAsyncRefresh().
|
final |
Fetch the value of a key from cache.
If supplied, $curTTL is set to the remaining TTL (current time left):
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:
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:
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 metadata map. This map includes the following metadata:
Otherwise, $info will transform into the cached value timestamp.
string | $key | Cache key made from makeKey()/makeGlobalKey() |
mixed | null | &$curTTL | Approximate TTL left on the key if present/tombstoned [returned] |
string[] | $checkKeys | The "check" keys used to validate the value |
mixed | null | &$info | Key info if WANObjectCache::PASS_BY_REF [returned] |
Definition at line 402 of file WANObjectCache.php.
References getMulti().
|
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.
string | $key |
Definition at line 868 of file WANObjectCache.php.
References getMultiCheckKeyTime().
|
protected |
Definition at line 2847 of file WANObjectCache.php.
Referenced by adaptiveTTL(), fetchOrRegenerate(), getInterimValue(), getMulti(), getMultiCheckKeyTime(), relayPurge(), set(), setInterimValue(), and yieldStampedeLock().
|
private |
string | $key | |
float | $minAsOf | Minimum acceptable "as of" timestamp |
Definition at line 1772 of file WANObjectCache.php.
References getCurrentTime(), isValid(), makeSisterKey(), unwrap(), and useInterimHoldOffCaching().
Referenced by fetchOrRegenerate().
|
final |
Get the "last error" registered; clearLastError() should be called manually.
Definition at line 2276 of file WANObjectCache.php.
|
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 metadata 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.
$checkKeys holds the "check" keys used to validate values of applicable keys. The integer indexes hold "check" keys that apply to all of $keys while the string indexes hold "check" keys that only apply to the cache key with that name.
string[] | $keys | List/map with cache keys made from makeKey()/makeGlobalKey() as values |
mixed | null | &$curTTLs | Map of (key => TTL left) for existing/tombstoned keys [returned] |
string[] | string[][] | $checkKeys | Map of (integer or cache key => "check" key(s)) |
mixed | null | &$info | Map of (key => info) if WANObjectCache::PASS_BY_REF [returned] |
Definition at line 446 of file WANObjectCache.php.
References $keys, getCurrentTime(), makeSisterKey(), makeSisterKeys(), processCheckKeys(), and unwrap().
Referenced by get(), and getMultiWithUnionSetCallback().
|
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:
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:
string[] | $keys |
Definition at line 933 of file WANObjectCache.php.
References $keys, getCurrentTime(), makePurgeValue(), makeSisterKey(), and parsePurgeValue().
Referenced by getCheckKeyTime().
|
final |
Method to fetch multiple cache keys at once with regeneration.
This works the same as getWithSetCallback() except:
Example usage:
ArrayIterator | $keyedIds | Result of WANObjectCache::makeMultiKeys() |
int | $ttl | Seconds to live for key updates |
callable | $callback | Callback the yields entity regeneration callbacks |
array | $opts | Options map |
Definition at line 1882 of file WANObjectCache.php.
References getNonProcessCachedMultiKeys(), getRawKeysForWarmup(), and getWithSetCallback().
|
final |
Method to fetch/regenerate multiple cache keys at once.
This works the same as getWithSetCallback() except:
Example usage:
ArrayIterator | $keyedIds | Result of WANObjectCache::makeMultiKeys() |
int | $ttl | Seconds to live for key updates |
callable | $callback | Callback the yields entity regeneration callbacks |
array | $opts | Options map |
Definition at line 1981 of file WANObjectCache.php.
References getMulti(), getNonProcessCachedMultiKeys(), getRawKeysForWarmup(), and getWithSetCallback().
|
private |
ArrayIterator | $keys | |
array | $opts |
Definition at line 2794 of file WANObjectCache.php.
References $keys, and getProcessCache().
Referenced by getMultiWithSetCallback(), and getMultiWithUnionSetCallback().
|
private |
string | $group |
Definition at line 2768 of file WANObjectCache.php.
Referenced by getNonProcessCachedMultiKeys(), and getWithSetCallback().
|
private |
string | $key | |
int | $version |
Definition at line 2785 of file WANObjectCache.php.
Referenced by getWithSetCallback().
WANObjectCache::getQoS | ( | $flag | ) |
int | $flag | ATTR_* class constant |
Definition at line 2335 of file WANObjectCache.php.
|
private |
string[] | $keys | |
string[] | string[][] | $checkKeys |
Definition at line 2816 of file WANObjectCache.php.
References $keys, $warmupCache, makeSisterKey(), and makeSisterKeys().
Referenced by getMultiWithSetCallback(), and getMultiWithUnionSetCallback().
|
final |
Definition at line 2417 of file WANObjectCache.php.
|
final |
Method to fetch/regenerate a cache key.
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:
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:
Example usage (typical key):
Example usage (key that is expensive and hot):
Example usage (key with dynamic dependencies):
Example usage (key that is expensive with too many DB dependencies for "check keys"):
Example usage (hot key holding most recent 100 events):
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):
string | $key | Cache key made from makeKey()/makeGlobalKey() |
int | $ttl | Nominal seconds-to-live for newly computed values. Special values are:
|
callable | $callback | Value generation function |
array | $opts | Options map:
|
array | $cbParams | Custom field/value map to pass to the callback (since 1.35) |
-param array{checkKeys?:string[],graceTTL?:int,lockTSE?:int,busyValue?:mixed,pcTTL?:int,pcGroup?:string,version?:int,minAsOf?:int,hotTTR?:int,lowTTL?:int,ageNew?:int,staleTTL?:int,touchedCallback?:callable} $opts
Definition at line 1356 of file WANObjectCache.php.
References $res, fetchOrRegenerate(), getProcessCache(), getProcessCacheKey(), and makeGlobalKey().
Referenced by getMultiWithSetCallback(), and getMultiWithUnionSetCallback().
WANObjectCache::hash256 | ( | $component | ) |
Hash a possibly long string into a suitable component for makeKey()/makeGlobalKey()
string | $component | A raw component used in building a cache key |
Definition at line 2149 of file WANObjectCache.php.
|
private |
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.
float | $curTTL | Approximate TTL left on the key if present |
int | $graceTTL | Consider using stale values if $curTTL is greater than this |
Definition at line 2512 of file WANObjectCache.php.
References worthRefreshExpiring().
Referenced by fetchOrRegenerate().
|
protected |
Check if $value is not false, versioned (if needed), and not older than $minTime (if set)
array | bool | $value | |
float | $asOf | The time $value was generated |
float | $minAsOf | Minimum acceptable "as of" timestamp |
float | null | $purgeTime | The last time the value was invalidated |
Definition at line 2622 of file WANObjectCache.php.
Referenced by fetchOrRegenerate(), and getInterimValue().
|
private |
float | $age | Age of volatile/interim key in seconds |
Definition at line 1658 of file WANObjectCache.php.
Referenced by fetchOrRegenerate().
WANObjectCache::makeGlobalKey | ( | $class, | |
$components | |||
) |
string | $class | Key class |
string|int | ...$components Key components (starting with a key collection name) |
Implements IStoreKeyEncoder.
Definition at line 2138 of file WANObjectCache.php.
Referenced by getWithSetCallback().
WANObjectCache::makeKey | ( | $class, | |
$components | |||
) |
string | $class | Key class |
string|int | ...$components Key components (starting with a key collection name) |
Implements IStoreKeyEncoder.
Definition at line 2127 of file WANObjectCache.php.
|
final |
Get an iterator of (cache key => entity ID) for a list of entity IDs.
The callback takes an ID string and returns a key via makeKey()/makeGlobalKey(). There should be no network nor filesystem I/O used in the callback. The entity ID/key mapping must be 1:1 or an exception will be thrown. If hashing is needed, then use the hash256() method.
Example usage for the default keyspace:
Example usage for mixed default and global keyspace:
Example usage with hashing:
string[] | int[] | $ids | List of entity IDs |
callable | $keyCallback | Function returning makeKey()/makeGlobalKey() on the input ID |
UnexpectedValueException |
Definition at line 2203 of file WANObjectCache.php.
|
private |
float | $timestamp | |
int | $holdoff | In seconds |
Definition at line 2760 of file WANObjectCache.php.
Referenced by getMultiCheckKeyTime(), processCheckKeys(), and relayPurge().
|
private |
Get a cache key that should be collocated with a base key.
string | $baseKey | Cache key made from makeKey()/makeGlobalKey() |
string | $typeChar | Consistent hashing agnostic suffix character matching [a-zA-Z] |
Definition at line 1633 of file WANObjectCache.php.
References true.
Referenced by checkAndSetCooloff(), claimStampedeLock(), delete(), getInterimValue(), getMulti(), getMultiCheckKeyTime(), getRawKeysForWarmup(), makeSisterKeys(), reap(), reapCheckKey(), resetCheckKey(), set(), setInterimValue(), touchCheckKey(), and yieldStampedeLock().
|
private |
Get cache keys that should be collocated with their corresponding base keys.
string[] | $baseKeys | Cache keys made from makeKey()/makeGlobalKey() |
string | $type | Consistent hashing agnostic suffix character matching [a-zA-Z] |
Definition at line 1617 of file WANObjectCache.php.
References $keys, $type, and makeSisterKey().
Referenced by getMulti(), and getRawKeysForWarmup().
|
final |
Get an (ID => value) map from (i) a non-unique list of entity IDs, and (ii) the list of corresponding entity values by first appearance of each ID in the entity ID list.
For use with getMultiWithSetCallback() and getMultiWithUnionSetCallback().
Only use this method if the entity ID/key mapping is trivially 1:1 without exception. Key generation method must utitilize the full entity ID in the key (not a hash of it).
Example usage:
string[] | int[] | $ids | Entity ID list makeMultiKeys() |
mixed[] | $res | Result of getMultiWithSetCallback()/getMultiWithUnionSetCallback() |
Definition at line 2259 of file WANObjectCache.php.
References $res.
|
static |
Get an instance that wraps EmptyBagOStuff.
Definition at line 348 of file WANObjectCache.php.
|
private |
string | array | bool | $value | Possible string of the form "PURGED:<timestamp>:<holdoff>" |
Definition at line 2725 of file WANObjectCache.php.
Referenced by getMultiCheckKeyTime(), processCheckKeys(), reapCheckKey(), and unwrap().
|
private |
string[] | $timeKeys | List of prefixed time check keys |
mixed[] | $wrappedValues | Preloaded map of (key => value) |
float | $now |
Definition at line 557 of file WANObjectCache.php.
References makePurgeValue(), and parsePurgeValue().
Referenced by getMulti().
|
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.
string | $key | Cache key |
int | $purgeTimestamp | UNIX timestamp of purge |
bool | &$isStale | Whether the key is stale |
Definition at line 2065 of file WANObjectCache.php.
References makeSisterKey().
|
final |
Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp.
string | $key | Cache key |
int | $purgeTimestamp | UNIX timestamp of purge |
bool | &$isStale | Whether the key is stale |
Definition at line 2097 of file WANObjectCache.php.
References makeSisterKey(), and parsePurgeValue().
|
protected |
Do the actual async bus delete of a key.
string | $key | Sister cache key |
Definition at line 2458 of file WANObjectCache.php.
Referenced by delete(), and resetCheckKey().
|
protected |
Do the actual async bus purge of a key.
This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
string | $key | Sister cache key |
int | $ttl | Seconds to keep the tombstone around |
int | $holdoff | HOLDOFF_* constant controlling how long to ignore sets for this key |
Definition at line 2431 of file WANObjectCache.php.
References getCurrentTime(), and makePurgeValue().
Referenced by delete(), and touchCheckKey().
|
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:
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.
string | $key | Cache key |
Definition at line 1039 of file WANObjectCache.php.
References determineKeyClassForStats(), makeSisterKey(), and relayDelete().
|
private |
mixed | $busyValue |
Definition at line 1814 of file WANObjectCache.php.
Referenced by fetchOrRegenerate().
|
private |
mixed | $value | |
float | null | $curTTL | |
array | $curInfo | |
callable | null | $touchedCallback |
Definition at line 1741 of file WANObjectCache.php.
Referenced by fetchOrRegenerate().
|
private |
mixed | $value | |
float | null | $lastPurge | |
callable | null | $touchedCallback |
Definition at line 1761 of file WANObjectCache.php.
Referenced by fetchOrRegenerate().
|
private |
Schedule a deferred cache regeneration if possible.
string | $key | |
int | $ttl | Seconds to live |
callable | $callback | |
array | $opts | |
array | $cbParams |
Definition at line 2482 of file WANObjectCache.php.
References fetchOrRegenerate().
Referenced by fetchOrRegenerate().
|
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:
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:
string | $key | Cache key |
mixed | $value | |
int | $ttl | Seconds to live. Special values are:
|
array | $opts | Options map:
|
-param array{lag?:int,since?:int,pending?:bool,lockTSE?:int,staleTTL?:int,creating?:bool,version?:?string,walltime?:int|float} $opts
Definition at line 651 of file WANObjectCache.php.
References $cache, getCurrentTime(), makeSisterKey(), and wrap().
Referenced by MessageBlobStore\recacheMessageBlob().
|
private |
string | $key | |
mixed | $value | |
int | $ttl | |
int | null | $version | Value version number |
float | $walltime | How long it took to generate the value in seconds |
Definition at line 1796 of file WANObjectCache.php.
References getCurrentTime(), makeSisterKey(), and wrap().
Referenced by fetchOrRegenerate().
WANObjectCache::setLogger | ( | LoggerInterface | $logger | ) |
LoggerInterface | $logger |
Definition at line 339 of file WANObjectCache.php.
Referenced by __construct().
WANObjectCache::setMockTime | ( | & | $time | ) |
float | null | &$time | Mock UNIX timestamp for testing |
Definition at line 2865 of file WANObjectCache.php.
|
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.
string | $key | Cache key |
int | $holdoff | HOLDOFF_TTL or HOLDOFF_TTL_NONE constant |
Definition at line 998 of file WANObjectCache.php.
References determineKeyClassForStats(), makeSisterKey(), and relayPurge().
|
private |
array | string | bool | $wrapped | The entry at a cache key |
float | $now | Unix Current timestamp (preferrably pre-query) |
Definition at line 2673 of file WANObjectCache.php.
References parsePurgeValue().
Referenced by getInterimValue(), and getMulti().
|
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:
This is useful when both:
bool | $enabled | Whether to enable interim caching |
Definition at line 2326 of file WANObjectCache.php.
References useInterimHoldOffCaching().
Referenced by getInterimValue(), and useInterimHoldOffCaching().
|
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.
float | $curTTL | Approximate TTL left on the key if present |
float | $lowTTL | Consider a refresh when $curTTL is less than this |
Definition at line 2542 of file WANObjectCache.php.
Referenced by fetchOrRegenerate(), and isAliveOrInGracePeriod().
|
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.
float | $asOf | UNIX timestamp of the value |
int | $ageNew | Age of key when this might recommend refreshing (seconds) |
int | $timeTillRefresh | Age of key when it should be refreshed if popular (seconds) |
float | $now | The current UNIX timestamp |
Definition at line 2579 of file WANObjectCache.php.
Referenced by fetchOrRegenerate().
|
private |
mixed | $value | |
int | $ttl | Seconds to live or zero for "indefinite" |
int | null | $version | Value version number or null if not versioned |
float | $now | Unix Current timestamp just before calling set() |
float | null | $walltime | How long it took to generate the value in seconds |
Definition at line 2643 of file WANObjectCache.php.
Referenced by set(), and setInterimValue().
|
private |
string | $key | |
bool | $hasLock |
Definition at line 1598 of file WANObjectCache.php.
References getCurrentTime(), and makeSisterKey().
Referenced by fetchOrRegenerate().
|
protected |
Function that takes a WAN cache callback and runs it later.
Definition at line 135 of file WANObjectCache.php.
|
protected |
The local datacenter cache.
Definition at line 127 of file WANObjectCache.php.
|
private |
Callback stack depth for getWithSetCallback()
Definition at line 160 of file WANObjectCache.php.
|
staticprivate |
Seconds to keep dependency purge keys around.
Definition at line 213 of file WANObjectCache.php.
|
protected |
Cache cluster name for mcrouter use.
Definition at line 142 of file WANObjectCache.php.
|
protected |
Whether "sister" keys should be coalesced to the same cache server.
Definition at line 150 of file WANObjectCache.php.
|
protected |
Scheme to use for key coalescing (Hash Tags or Hash Stops)
Definition at line 152 of file WANObjectCache.php.
|
staticprivate |
Seconds to no-op key set() calls to avoid large blob I/O stampedes.
Definition at line 220 of file WANObjectCache.php.
|
protected |
Unix timestamp of the oldest possible valid values.
Definition at line 146 of file WANObjectCache.php.
|
staticprivate |
@noinspection PhpUnusedPrivateFieldInspection
Key to the flags bit field (reserved number)
Definition at line 254 of file WANObjectCache.php.
|
staticprivate |
Key to WAN cache version number.
Definition at line 246 of file WANObjectCache.php.
|
staticprivate |
Key to how long it took to generate the value.
Definition at line 258 of file WANObjectCache.php.
|
staticprivate |
Key to the cache timestamp.
Definition at line 252 of file WANObjectCache.php.
|
staticprivate |
Key to the original TTL.
Definition at line 250 of file WANObjectCache.php.
|
staticprivate |
Key to the cached value.
Definition at line 248 of file WANObjectCache.php.
|
staticprivate |
Key to collection cache version number.
Definition at line 256 of file WANObjectCache.php.
|
staticprivate |
Consider value generation slow if it takes more than this many seconds.
Definition at line 235 of file WANObjectCache.php.
|
staticprivate |
Seconds to keep interim value keys for tombstoned keys around.
Definition at line 215 of file WANObjectCache.php.
|
private |
Reads/second assumed during a hypothetical cache write stampede for a key.
Definition at line 155 of file WANObjectCache.php.
|
private |
Max tolerable bytes/second to spend on a cache write stampede for a key.
Definition at line 157 of file WANObjectCache.php.
|
staticprivate |
Seconds to keep lock keys around.
Definition at line 218 of file WANObjectCache.php.
|
protected |
Definition at line 131 of file WANObjectCache.php.
|
protected |
Whether to use mcrouter key prefixing for routing.
Definition at line 138 of file WANObjectCache.php.
|
protected |
Map of group PHP instance caches.
Definition at line 129 of file WANObjectCache.php.
|
staticprivate |
Key to the tombstone entry hold-off TTL.
Definition at line 240 of file WANObjectCache.php.
|
staticprivate |
Key to the tombstone entry timestamp.
Definition at line 238 of file WANObjectCache.php.
|
staticprivate |
Prefix for tombstone key values.
Definition at line 272 of file WANObjectCache.php.
|
staticprivate |
Seconds to ramp up the chance of regeneration due to expected time-till-refresh.
Definition at line 222 of file WANObjectCache.php.
|
staticprivate |
Max millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL)
Definition at line 232 of file WANObjectCache.php.
|
staticprivate |
Min millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL)
Definition at line 230 of file WANObjectCache.php.
|
protected |
Physical region for mcrouter use.
Definition at line 140 of file WANObjectCache.php.
|
protected |
Stable secret used for hasing long strings into key components.
Definition at line 148 of file WANObjectCache.php.
|
protected |
Definition at line 133 of file WANObjectCache.php.
|
staticprivate |
Tiny negative float to use when CTL comes up >= 0 due to clock skew.
Definition at line 225 of file WANObjectCache.php.
|
staticprivate |
Tiny positive float to use when using "minTime" to assert an inequality.
Definition at line 227 of file WANObjectCache.php.
|
staticprivate |
Single character cool-off key component.
Definition at line 269 of file WANObjectCache.php.
|
staticprivate |
Single character interium key component.
Definition at line 267 of file WANObjectCache.php.
|
staticprivate |
Single character mutex key component.
Definition at line 265 of file WANObjectCache.php.
|
staticprivate |
Single character timestamp key component.
Definition at line 263 of file WANObjectCache.php.
|
staticprivate |
Single character value mutex key component.
Definition at line 261 of file WANObjectCache.php.
|
protected |
Whether to use "interim" caching while keys are tombstoned.
Definition at line 144 of file WANObjectCache.php.
|
staticprivate |
Cache format version number.
Definition at line 243 of file WANObjectCache.php.
|
private |
Definition at line 167 of file WANObjectCache.php.
|
private |
Temporary warm-up cache.
Definition at line 162 of file WANObjectCache.php.
Referenced by getRawKeysForWarmup().
|
private |
Key fetched.
Definition at line 164 of file WANObjectCache.php.