3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
22 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface
;
23 use Psr\Log\LoggerAwareInterface
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
28 * Multi-datacenter aware caching interface
30 * ### Using WANObjectCache
32 * All operations go to the local datacenter cache, except for delete(),
33 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
35 * This class is intended for caching data from primary stores.
36 * If the get() method does not return a value, then the caller
37 * should query the new value and backfill the cache using set().
38 * The preferred way to do this logic is through getWithSetCallback().
39 * When querying the store on cache miss, the closest DB replica
40 * should be used. Try to avoid heavyweight DB master or quorum reads.
42 * To ensure consumers of the cache see new values in a timely manner,
43 * you either need to follow either the validation strategy, or the
46 * The validation strategy refers to the natural avoidance of stale data
47 * by one of the following means:
49 * - A) The cached value is immutable.
50 * If the consumer has access to an identifier that uniquely describes a value,
51 * cached value need not change. Instead, the key can change. This also allows
52 * all servers to access their perceived current version. This is important
53 * in context of multiple deployed versions of your application and/or cross-dc
54 * database replication, to ensure deterministic values without oscillation.
55 * - B) Validity is checked against the source after get().
56 * This is the inverse of A. The unique identifier is embedded inside the value
57 * and validated after on retreival. If outdated, the value is recomputed.
58 * - C) The value is cached with a modest TTL (without validation).
59 * If value recomputation is reasonably performant, and the value is allowed to
60 * be stale, one should consider using TTL only – using the value's age as
61 * method of validation.
63 * The purge strategy refers to the the approach whereby your application knows that
64 * source data has changed and can react by purging the relevant cache keys.
65 * As purges are expensive, this strategy should be avoided if possible.
66 * The simplest purge method is delete().
68 * No matter which strategy you choose, callers must not rely on updates or purges
69 * being immediately visible to other servers. It should be treated similarly as
70 * one would a database replica.
72 * The need for immediate updates should be avoided. If needed, solutions must be
73 * sought outside WANObjectCache.
75 * ### Deploying WANObjectCache
77 * There are two supported ways to set up broadcasted operations:
79 * - A) Set up mcrouter as the underlying cache backend, using a memcached BagOStuff class
80 * for the 'cache' parameter. The 'region' and 'cluster' parameters must be provided
81 * and 'mcrouterAware' must be set to `true`.
82 * Configure mcrouter as follows:
83 * - 1) Use Route Prefixing based on region (datacenter) and cache cluster.
84 * See https://github.com/facebook/mcrouter/wiki/Routing-Prefix and
85 * https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup.
86 * - 2) To increase the consistency of delete() and touchCheckKey() during cache
87 * server membership changes, you can use the OperationSelectorRoute to
88 * configure 'set' and 'delete' operations to go to all servers in the cache
89 * cluster, instead of just one server determined by hashing.
90 * See https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles.
91 * - B) Set up dynomite as a cache middleware between the web servers and either memcached
92 * or redis and use it as the underlying cache backend, using a memcached BagOStuff
93 * class for the 'cache' parameter. This will broadcast all key setting operations,
94 * not just purges, which can be useful for cache warming. Writes are eventually
95 * consistent via the Dynamo replication model. See https://github.com/Netflix/dynomite.
97 * Broadcasted operations like delete() and touchCheckKey() are done asynchronously
98 * in all datacenters this way, though the local one should likely be near immediate.
100 * This means that callers in all datacenters may see older values for however many
101 * milliseconds that the purge took to reach that datacenter. As with any cache, this
102 * should not be relied on for cases where reads are used to determine writes to source
103 * (e.g. non-cache) data stores, except when reading immutable data.
105 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
106 * to avoid collisions with keys that are not wrapped as metadata arrays. The
107 * prefixes are as follows:
108 * - a) "WANCache:v" : used for regular value keys
109 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
110 * - c) "WANCache:t" : used for storing timestamp "check" keys
111 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
116 class WANObjectCache
implements IExpiringStore
, LoggerAwareInterface
{
117 /** @var BagOStuff The local datacenter cache */
119 /** @var MapCacheLRU[] Map of group PHP instance caches */
120 protected $processCaches = [];
121 /** @bar bool Whether to use mcrouter key prefixing for routing */
122 protected $mcrouterAware;
123 /** @var string Physical region for mcrouter use */
125 /** @var string Cache cluster name for mcrouter use */
127 /** @var LoggerInterface */
129 /** @var StatsdDataFactoryInterface */
131 /** @var bool Whether to use "interim" caching while keys are tombstoned */
132 protected $useInterimHoldOffCaching = true;
133 /** @var callable|null Function that takes a WAN cache callback and runs it later */
134 protected $asyncHandler;
135 /** @var float Unix timestamp of the oldest possible valid values */
138 /** @var int Callback stack depth for getWithSetCallback() */
139 private $callbackDepth = 0;
140 /** @var mixed[] Temporary warm-up cache */
141 private $warmupCache = [];
142 /** @var int Key fetched */
143 private $warmupKeyMisses = 0;
145 /** @var float|null */
146 private $wallClockOverride;
148 /** Max time expected to pass between delete() and DB commit finishing */
149 const MAX_COMMIT_DELAY
= 3;
150 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
151 const MAX_READ_LAG
= 7;
152 /** Seconds to tombstone keys on delete() */
153 const HOLDOFF_TTL
= 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
155 /** Seconds to keep dependency purge keys around */
156 const CHECK_KEY_TTL
= self
::TTL_YEAR
;
157 /** Seconds to keep interim value keys for tombstoned keys around */
158 const INTERIM_KEY_TTL
= 1;
160 /** Seconds to keep lock keys around */
162 /** Seconds to no-op key set() calls to avoid large blob I/O stampedes */
163 const COOLOFF_TTL
= 1;
164 /** Default remaining TTL at which to consider pre-emptive regeneration */
167 /** Never consider performing "popularity" refreshes until a key reaches this age */
169 /** The time length of the "popularity" refresh window for hot keys */
171 /** Hits/second for a refresh to be expected within the "popularity" window */
172 const HIT_RATE_HIGH
= 1;
173 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
174 const RAMPUP_TTL
= 30;
176 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
177 const TTL_UNCACHEABLE
= -1;
178 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
180 /** Max TTL to store keys when a data sourced is lagged */
181 const TTL_LAGGED
= 30;
182 /** Idiom for delete() for "no hold-off" */
183 const HOLDOFF_NONE
= 0;
184 /** Idiom for set()/getWithSetCallback() for "do not augment the storage medium TTL" */
185 const STALE_TTL_NONE
= 0;
186 /** Idiom for set()/getWithSetCallback() for "no post-expired grace period" */
187 const GRACE_TTL_NONE
= 0;
189 /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
190 const MIN_TIMESTAMP_NONE
= 0.0;
192 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
193 const TINY_NEGATIVE
= -0.000001;
195 /** Seconds of delay after get() where set() storms are a consideration with 'lockTSE' */
196 const SET_DELAY_HIGH_SEC
= 0.1;
198 /** Cache format version number */
201 const FLD_VERSION
= 0; // key to cache version number
202 const FLD_VALUE
= 1; // key to the cached value
203 const FLD_TTL
= 2; // key to the original TTL
204 const FLD_TIME
= 3; // key to the cache time
205 const FLD_FLAGS
= 4; // key to the flags bitfield (reserved number)
206 const FLD_HOLDOFF
= 5; // key to any hold-off TTL
208 const ERR_NONE
= 0; // no error
209 const ERR_NO_RESPONSE
= 1; // no response
210 const ERR_UNREACHABLE
= 2; // can't connect
211 const ERR_UNEXPECTED
= 3; // response gave some error
212 const ERR_RELAY
= 4; // relay broadcast failed
214 const VALUE_KEY_PREFIX
= 'WANCache:v:';
215 const INTERIM_KEY_PREFIX
= 'WANCache:i:';
216 const TIME_KEY_PREFIX
= 'WANCache:t:';
217 const MUTEX_KEY_PREFIX
= 'WANCache:m:';
218 const COOLOFF_KEY_PREFIX
= 'WANCache:c:';
220 const PURGE_VAL_PREFIX
= 'PURGED:';
222 const VFLD_DATA
= 'WOC:d'; // key to the value of versioned data
223 const VFLD_VERSION
= 'WOC:v'; // key to the version of the value present
225 const PC_PRIMARY
= 'primary:1000'; // process cache name and max key count
228 * @param array $params
229 * - cache : BagOStuff object for a persistent cache
230 * - logger : LoggerInterface object
231 * - stats : LoggerInterface object
232 * - asyncHandler : A function that takes a callback and runs it later. If supplied,
233 * whenever a preemptive refresh would be triggered in getWithSetCallback(), the
234 * current cache value is still used instead. However, the async-handler function
235 * receives a WAN cache callback that, when run, will execute the value generation
236 * callback supplied by the getWithSetCallback() caller. The result will be saved
237 * as normal. The handler is expected to call the WAN cache callback at an opportune
238 * time (e.g. HTTP post-send), though generally within a few 100ms. [optional]
239 * - region: the current physical region. This is required when using mcrouter as the
240 * backing store proxy. [optional]
241 * - cluster: name of the cache cluster used by this WAN cache. The name must be the
242 * same in all datacenters; the ("region","cluster") tuple is what distinguishes
243 * the counterpart cache clusters among all the datacenter. The contents of
244 * https://github.com/facebook/mcrouter/wiki/Config-Files give background on this.
245 * This is required when using mcrouter as the backing store proxy. [optional]
246 * - mcrouterAware: set as true if mcrouter is the backing store proxy and mcrouter
247 * is configured to interpret /<region>/<cluster>/ key prefixes as routes. This
248 * requires that "region" and "cluster" are both set above. [optional]
249 * - epoch: lowest UNIX timestamp a value/tombstone must have to be valid. [optional]
251 public function __construct( array $params ) {
252 $this->cache
= $params['cache'];
253 $this->region
= $params['region'] ??
'main';
254 $this->cluster
= $params['cluster'] ??
'wan-main';
255 $this->mcrouterAware
= !empty( $params['mcrouterAware'] );
256 $this->epoch
= $params['epoch'] ??
1.0;
258 $this->setLogger( $params['logger'] ??
new NullLogger() );
259 $this->stats
= $params['stats'] ??
new NullStatsdDataFactory();
260 $this->asyncHandler
= $params['asyncHandler'] ??
null;
264 * @param LoggerInterface $logger
266 public function setLogger( LoggerInterface
$logger ) {
267 $this->logger
= $logger;
271 * Get an instance that wraps EmptyBagOStuff
273 * @return WANObjectCache
275 public static function newEmpty() {
277 'cache' => new EmptyBagOStuff()
282 * Fetch the value of a key from cache
284 * If supplied, $curTTL is set to the remaining TTL (current time left):
285 * - a) INF; if $key exists, has no TTL, and is not invalidated by $checkKeys
286 * - b) float (>=0); if $key exists, has a TTL, and is not invalidated by $checkKeys
287 * - c) float (<0); if $key is tombstoned, stale, or existing but invalidated by $checkKeys
288 * - d) null; if $key does not exist and is not tombstoned
290 * If a key is tombstoned, $curTTL will reflect the time since delete().
292 * The timestamp of $key will be checked against the last-purge timestamp
293 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
294 * initialized to the current timestamp. If any of $checkKeys have a timestamp
295 * greater than that of $key, then $curTTL will reflect how long ago $key
296 * became invalid. Callers can use $curTTL to know when the value is stale.
297 * The $checkKeys parameter allow mass invalidations by updating a single key:
298 * - a) Each "check" key represents "last purged" of some source data
299 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
300 * - c) When the source data that "check" keys represent changes,
301 * the touchCheckKey() method is called on them
303 * Source data entities might exists in a DB that uses snapshot isolation
304 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
305 * isolation can largely be maintained by doing the following:
306 * - a) Calling delete() on entity change *and* creation, before DB commit
307 * - b) Keeping transaction duration shorter than the delete() hold-off TTL
308 * - c) Disabling interim key caching via useInterimHoldOffCaching() before get() calls
310 * However, pre-snapshot values might still be seen if an update was made
311 * in a remote datacenter but the purge from delete() didn't relay yet.
313 * Consider using getWithSetCallback() instead of get() and set() cycles.
314 * That method has cache slam avoiding features for hot/expensive keys.
316 * @param string $key Cache key made from makeKey() or makeGlobalKey()
317 * @param mixed|null &$curTTL Approximate TTL left on the key if present/tombstoned [returned]
318 * @param array $checkKeys List of "check" keys
319 * @param float|null &$asOf UNIX timestamp of cached value; null on failure [returned]
320 * @return mixed Value of cache key or false on failure
322 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
325 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
326 $curTTL = $curTTLs[$key] ??
null;
327 $asOf = $asOfs[$key] ??
null;
329 return $values[$key] ??
false;
333 * Fetch the value of several keys from cache
335 * @see WANObjectCache::get()
337 * @param array $keys List of cache keys made from makeKey() or makeGlobalKey()
338 * @param array &$curTTLs Map of (key => approximate TTL left) for existing keys [returned]
339 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
340 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
341 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
342 * @return array Map of (key => value) for keys that exist and are not tombstoned
344 final public function getMulti(
345 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
351 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
352 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
354 $checkKeysForAll = [];
355 $checkKeysByKey = [];
357 foreach ( $checkKeys as $i => $checkKeyGroup ) {
358 $prefixed = self
::prefixCacheKeys( (array)$checkKeyGroup, self
::TIME_KEY_PREFIX
);
359 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
360 // Is this check keys for a specific cache key, or for all keys being fetched?
361 if ( is_int( $i ) ) {
362 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
364 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
365 ?
array_merge( $checkKeysByKey[$i], $prefixed )
370 // Fetch all of the raw values
371 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
372 if ( $this->warmupCache
) {
373 $wrappedValues = array_intersect_key( $this->warmupCache
, array_flip( $keysGet ) );
374 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) ); // keys left to fetch
375 $this->warmupKeyMisses +
= count( $keysGet );
380 $wrappedValues +
= $this->cache
->getMulti( $keysGet );
382 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
383 $now = $this->getCurrentTime();
385 // Collect timestamps from all "check" keys
386 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
387 $purgeValuesByKey = [];
388 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
389 $purgeValuesByKey[$cacheKey] =
390 $this->processCheckKeys( $checks, $wrappedValues, $now );
393 // Get the main cache value for each key and validate them
394 foreach ( $valueKeys as $vKey ) {
395 if ( !isset( $wrappedValues[$vKey] ) ) {
396 continue; // not found
399 $key = substr( $vKey, $vPrefixLen ); // unprefix
401 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
402 if ( $value !== false ) {
403 $result[$key] = $value;
404 // Force dependent keys to be seen as stale for a while after purging
405 // to reduce race conditions involving stale data getting cached
406 $purgeValues = $purgeValuesForAll;
407 if ( isset( $purgeValuesByKey[$key] ) ) {
408 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
410 foreach ( $purgeValues as $purge ) {
411 $safeTimestamp = $purge[self
::FLD_TIME
] +
$purge[self
::FLD_HOLDOFF
];
412 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
413 // How long ago this value was invalidated by *this* check key
414 $ago = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
415 // How long ago this value was invalidated by *any* known check key
416 $curTTL = min( $curTTL, $ago );
420 $curTTLs[$key] = $curTTL;
421 $asOfs[$key] = ( $value !== false ) ?
$wrappedValues[$vKey][self
::FLD_TIME
] : null;
429 * @param array $timeKeys List of prefixed time check keys
430 * @param array $wrappedValues
432 * @return array List of purge value arrays
434 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
436 foreach ( $timeKeys as $timeKey ) {
437 $purge = isset( $wrappedValues[$timeKey] )
438 ?
$this->parsePurgeValue( $wrappedValues[$timeKey] )
440 if ( $purge === false ) {
441 // Key is not set or malformed; regenerate
442 $newVal = $this->makePurgeValue( $now, self
::HOLDOFF_TTL
);
443 $this->cache
->add( $timeKey, $newVal, self
::CHECK_KEY_TTL
);
444 $purge = $this->parsePurgeValue( $newVal );
446 $purgeValues[] = $purge;
452 * Set the value of a key in cache
454 * Simply calling this method when source data changes is not valid because
455 * the changes do not replicate to the other WAN sites. In that case, delete()
456 * should be used instead. This method is intended for use on cache misses.
458 * If the data was read from a snapshot-isolated transactions (e.g. the default
459 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
461 * - b) T2 updates a row, calls delete(), and commits
462 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
463 * - d) T1 reads the row and calls set() due to a cache miss
464 * - e) Stale value is stuck in cache
466 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
468 * Be aware that this does not update the process cache for getWithSetCallback()
469 * callers. Keys accessed via that method are not generally meant to also be set
470 * using this primitive method.
472 * Do not use this method on versioned keys accessed via getWithSetCallback().
476 * $dbr = wfGetDB( DB_REPLICA );
477 * $setOpts = Database::getCacheSetOptions( $dbr );
478 * // Fetch the row from the DB
479 * $row = $dbr->selectRow( ... );
480 * $key = $cache->makeKey( 'building', $buildingId );
481 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
484 * @param string $key Cache key
485 * @param mixed $value
486 * @param int $ttl Seconds to live. Special values are:
487 * - WANObjectCache::TTL_INDEFINITE: Cache forever
488 * @param array $opts Options map:
489 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
490 * before the data was read or, if applicable, the replica DB lag before
491 * the snapshot-isolated transaction the data was read from started.
492 * Use false to indicate that replication is not running.
494 * - since : UNIX timestamp of the data in $value. Typically, this is either
495 * the current time the data was read or (if applicable) the time when
496 * the snapshot-isolated transaction the data was read from started.
498 * - pending : Whether this data is possibly from an uncommitted write transaction.
499 * Generally, other threads should not see values from the future and
500 * they certainly should not see ones that ended up getting rolled back.
502 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
503 * with this TTL and flag it as stale. This is only useful if the reads for this key
504 * use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set
505 * then it will still add on to this TTL in the excessive lag scenario.
506 * Default: WANObjectCache::TSE_NONE
507 * - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
508 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
509 * will call the regeneration callback in such cases, passing in the old value
510 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
511 * on the old value's as-of time when it is verified as still being correct.
512 * Default: WANObjectCache::STALE_TTL_NONE.
513 * @note Options added in 1.28: staleTTL
514 * @return bool Success
516 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
517 $now = $this->getCurrentTime();
518 $lockTSE = $opts['lockTSE'] ?? self
::TSE_NONE
;
519 $staleTTL = $opts['staleTTL'] ?? self
::STALE_TTL_NONE
;
520 $age = isset( $opts['since'] ) ?
max( 0, $now - $opts['since'] ) : 0;
521 $lag = $opts['lag'] ??
0;
523 // Do not cache potentially uncommitted data as it might get rolled back
524 if ( !empty( $opts['pending'] ) ) {
526 'Rejected set() for {cachekey} due to pending writes.',
527 [ 'cachekey' => $key ]
530 return true; // no-op the write for being unsafe
533 $logicalTTL = null; // logical TTL override
534 // Check if there's a risk of writing stale data after the purge tombstone expired
535 if ( $lag === false ||
( $lag +
$age ) > self
::MAX_READ_LAG
) {
536 // Case A: any long-running transaction
537 if ( $age > self
::MAX_READ_LAG
) {
538 if ( $lockTSE >= 0 ) {
539 // Store value as *almost* stale to avoid cache and mutex stampedes
540 $logicalTTL = self
::TTL_SECOND
;
542 'Lowered set() TTL for {cachekey} due to snapshot lag.',
543 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
547 'Rejected set() for {cachekey} due to snapshot lag.',
548 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
551 return true; // no-op the write for being unsafe
553 // Case B: high replication lag; lower TTL instead of ignoring all set()s
554 } elseif ( $lag === false ||
$lag > self
::MAX_READ_LAG
) {
555 if ( $lockTSE >= 0 ) {
556 $logicalTTL = min( $ttl ?
: INF
, self
::TTL_LAGGED
);
558 $ttl = min( $ttl ?
: INF
, self
::TTL_LAGGED
);
560 $this->logger
->warning(
561 'Lowered set() TTL for {cachekey} due to replication lag.',
562 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
564 // Case C: medium length request with medium replication lag
566 if ( $lockTSE >= 0 ) {
567 // Store value as *almost* stale to avoid cache and mutex stampedes
568 $logicalTTL = self
::TTL_SECOND
;
570 'Lowered set() TTL for {cachekey} due to high read lag.',
571 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
575 'Rejected set() for {cachekey} due to high read lag.',
576 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
579 return true; // no-op the write for being unsafe
584 // Wrap that value with time/TTL/version metadata
585 $wrapped = $this->wrap( $value, $logicalTTL ?
: $ttl, $now );
587 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
588 return ( is_string( $cWrapped ) )
589 ?
false // key is tombstoned; do nothing
593 return $this->cache
->merge( self
::VALUE_KEY_PREFIX
. $key, $func, $ttl +
$staleTTL, 1 );
597 * Purge a key from all datacenters
599 * This should only be called when the underlying data (being cached)
600 * changes in a significant way. This deletes the key and starts a hold-off
601 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
602 * This is done to avoid the following race condition:
603 * - a) Some DB data changes and delete() is called on a corresponding key
604 * - b) A request refills the key with a stale value from a lagged DB
605 * - c) The stale value is stuck there until the key is expired/evicted
607 * This is implemented by storing a special "tombstone" value at the cache
608 * key that this class recognizes; get() calls will return false for the key
609 * and any set() calls will refuse to replace tombstone values at the key.
610 * For this to always avoid stale value writes, the following must hold:
611 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
612 * - b) If lag is higher, the DB will have gone into read-only mode already
614 * Note that set() can also be lag-aware and lower the TTL if it's high.
616 * Be aware that this does not clear the process cache. Even if it did, callbacks
617 * used by getWithSetCallback() might still return stale data in the case of either
618 * uncommitted or not-yet-replicated changes (callback generally use replica DBs).
620 * When using potentially long-running ACID transactions, a good pattern is
621 * to use a pre-commit hook to issue the delete. This means that immediately
622 * after commit, callers will see the tombstone in cache upon purge relay.
623 * It also avoids the following race condition:
624 * - a) T1 begins, changes a row, and calls delete()
625 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
626 * - c) T2 starts, reads the row and calls set() due to a cache miss
627 * - d) T1 finally commits
628 * - e) Stale value is stuck in cache
632 * $dbw->startAtomic( __METHOD__ ); // start of request
633 * ... <execute some stuff> ...
634 * // Update the row in the DB
635 * $dbw->update( ... );
636 * $key = $cache->makeKey( 'homes', $homeId );
637 * // Purge the corresponding cache entry just before committing
638 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
639 * $cache->delete( $key );
641 * ... <execute some stuff> ...
642 * $dbw->endAtomic( __METHOD__ ); // end of request
645 * The $ttl parameter can be used when purging values that have not actually changed
646 * recently. For example, a cleanup script to purge cache entries does not really need
647 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
648 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
650 * If called twice on the same key, then the last hold-off TTL takes precedence. For
651 * idempotence, the $ttl should not vary for different delete() calls on the same key.
653 * @param string $key Cache key
654 * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
655 * @return bool True if the item was purged or not found, false on failure
657 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
658 $key = self
::VALUE_KEY_PREFIX
. $key;
661 // Publish the purge to all datacenters
662 $ok = $this->relayDelete( $key );
664 // Publish the purge to all datacenters
665 $ok = $this->relayPurge( $key, $ttl, self
::HOLDOFF_NONE
);
672 * Fetch the value of a timestamp "check" key
674 * The key will be *initialized* to the current time if not set,
675 * so only call this method if this behavior is actually desired
677 * The timestamp can be used to check whether a cached value is valid.
678 * Callers should not assume that this returns the same timestamp in
679 * all datacenters due to relay delays.
681 * The level of staleness can roughly be estimated from this key, but
682 * if the key was evicted from cache, such calculations may show the
683 * time since expiry as ~0 seconds.
685 * Note that "check" keys won't collide with other regular keys.
688 * @return float UNIX timestamp
690 final public function getCheckKeyTime( $key ) {
691 return $this->getMultiCheckKeyTime( [ $key ] )[$key];
695 * Fetch the values of each timestamp "check" key
697 * This works like getCheckKeyTime() except it takes a list of keys
698 * and returns a map of timestamps instead of just that of one key
700 * This might be useful if both:
701 * - a) a class of entities each depend on hundreds of other entities
702 * - b) these other entities are depended upon by millions of entities
704 * The later entities can each use a "check" key to invalidate their dependee entities.
705 * However, it is expensive for the former entities to verify against all of the relevant
706 * "check" keys during each getWithSetCallback() call. A less expensive approach is to do
707 * these verifications only after a "time-till-verify" (TTV) has passed. This is a middle
708 * ground between using blind TTLs and using constant verification. The adaptiveTTL() method
709 * can be used to dynamically adjust the TTV. Also, the initial TTV can make use of the
710 * last-modified times of the dependant entities (either from the DB or the "check" keys).
714 * $value = $cache->getWithSetCallback(
715 * $cache->makeGlobalKey( 'wikibase-item', $id ),
716 * self::INITIAL_TTV, // initial time-till-verify
717 * function ( $oldValue, &$ttv, &$setOpts, $oldAsOf ) use ( $checkKeys, $cache ) {
718 * $now = microtime( true );
719 * // Use $oldValue if it passes max ultimate age and "check" key comparisons
721 * $oldAsOf > max( $cache->getMultiCheckKeyTime( $checkKeys ) ) &&
722 * ( $now - $oldValue['ctime'] ) <= self::MAX_CACHE_AGE
724 * // Increase time-till-verify by 50% of last time to reduce overhead
725 * $ttv = $cache->adaptiveTTL( $oldAsOf, self::MAX_TTV, self::MIN_TTV, 1.5 );
726 * // Unlike $oldAsOf, "ctime" is the ultimate age of the cached data
730 * $mtimes = []; // dependency last-modified times; passed by reference
731 * $value = [ 'data' => $this->fetchEntityData( $mtimes ), 'ctime' => $now ];
732 * // Guess time-till-change among the dependencies, e.g. 1/(total change rate)
733 * $ttc = 1 / array_sum( array_map(
734 * function ( $mtime ) use ( $now ) {
735 * return 1 / ( $mtime ? ( $now - $mtime ) : 900 );
739 * // The time-to-verify should not be overly pessimistic nor optimistic
740 * $ttv = min( max( $ttc, self::MIN_TTV ), self::MAX_TTV );
744 * [ 'staleTTL' => $cache::TTL_DAY ] // keep around to verify and re-save
748 * @see WANObjectCache::getCheckKeyTime()
749 * @see WANObjectCache::getWithSetCallback()
752 * @return float[] Map of (key => UNIX timestamp)
755 final public function getMultiCheckKeyTime( array $keys ) {
757 foreach ( $keys as $key ) {
758 $rawKeys[$key] = self
::TIME_KEY_PREFIX
. $key;
761 $rawValues = $this->cache
->getMulti( $rawKeys );
762 $rawValues +
= array_fill_keys( $rawKeys, false );
765 foreach ( $rawKeys as $key => $rawKey ) {
766 $purge = $this->parsePurgeValue( $rawValues[$rawKey] );
767 if ( $purge !== false ) {
768 $time = $purge[self
::FLD_TIME
];
770 // Casting assures identical floats for the next getCheckKeyTime() calls
771 $now = (string)$this->getCurrentTime();
774 $this->makePurgeValue( $now, self
::HOLDOFF_TTL
),
780 $times[$key] = $time;
787 * Purge a "check" key from all datacenters, invalidating keys that use it
789 * This should only be called when the underlying data (being cached)
790 * changes in a significant way, and it is impractical to call delete()
791 * on all keys that should be changed. When get() is called on those
792 * keys, the relevant "check" keys must be supplied for this to work.
794 * The "check" key essentially represents a last-modified time of an entity.
795 * When the key is touched, the timestamp will be updated to the current time.
796 * Keys using the "check" key via get(), getMulti(), or getWithSetCallback() will
797 * be invalidated. This approach is useful if many keys depend on a single entity.
799 * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the
800 * future by get*() methods in order to avoid race conditions where keys are updated
801 * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check"
802 * key, making it possible to know the timestamp of the last change to the corresponding
803 * entities in most cases. This might use more cache space than resetCheckKey().
805 * When a few important keys get a large number of hits, a high cache time is usually
806 * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate
807 * in such cases since the "time since expiry" cannot be inferred, causing any get()
808 * after the reset to treat the key as being "hot", resulting in more stale value usage.
810 * Note that "check" keys won't collide with other regular keys.
812 * @see WANObjectCache::get()
813 * @see WANObjectCache::getWithSetCallback()
814 * @see WANObjectCache::resetCheckKey()
816 * @param string $key Cache key
817 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
818 * @return bool True if the item was purged or not found, false on failure
820 final public function touchCheckKey( $key, $holdoff = self
::HOLDOFF_TTL
) {
821 // Publish the purge to all datacenters
822 return $this->relayPurge( self
::TIME_KEY_PREFIX
. $key, self
::CHECK_KEY_TTL
, $holdoff );
826 * Delete a "check" key from all datacenters, invalidating keys that use it
828 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
829 * or getWithSetCallback() will be invalidated. The differences are:
830 * - a) The "check" key will be deleted from all caches and lazily
831 * re-initialized when accessed (rather than set everywhere)
832 * - b) Thus, dependent keys will be known to be stale, but not
833 * for how long (they are treated as "just" purged), which
834 * effects any lockTSE logic in getWithSetCallback()
835 * - c) Since "check" keys are initialized only on the server the key hashes
836 * to, any temporary ejection of that server will cause the value to be
837 * seen as purged as a new server will initialize the "check" key.
839 * The advantage here is that the "check" keys, which have high TTLs, will only
840 * be created when a get*() method actually uses that key. This is better when
841 * a large number of "check" keys are invalided in a short period of time.
843 * Note that "check" keys won't collide with other regular keys.
845 * @see WANObjectCache::get()
846 * @see WANObjectCache::getWithSetCallback()
847 * @see WANObjectCache::touchCheckKey()
849 * @param string $key Cache key
850 * @return bool True if the item was purged or not found, false on failure
852 final public function resetCheckKey( $key ) {
853 // Publish the purge to all datacenters
854 return $this->relayDelete( self
::TIME_KEY_PREFIX
. $key );
858 * Method to fetch/regenerate cache keys
860 * On cache miss, the key will be set to the callback result via set()
861 * (unless the callback returns false) and that result will be returned.
862 * The arguments supplied to the callback are:
863 * - $oldValue : current cache value or false if not present
864 * - &$ttl : a reference to the TTL which can be altered
865 * - &$setOpts : a reference to options for set() which can be altered
866 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
868 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
869 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
870 * value, but it can be used to maintain "most recent X" values that come from time or
871 * sequence based source data, provided that the "as of" id/time is tracked. Note that
872 * preemptive regeneration and $checkKeys can result in a non-false current value.
874 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
875 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
876 * regeneration will automatically be triggered using the callback.
878 * The $ttl argument and "hotTTR" option (in $opts) use time-dependant randomization
879 * to avoid stampedes. Keys that are slow to regenerate and either heavily used
880 * or subject to explicit (unpredictable) purges, may need additional mechanisms.
881 * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts).
882 * If explicit purges are needed, also:
883 * - a) Pass $key into $checkKeys
884 * - b) Use touchCheckKey( $key ) instead of delete( $key )
886 * Example usage (typical key):
888 * $catInfo = $cache->getWithSetCallback(
889 * // Key to store the cached value under
890 * $cache->makeKey( 'cat-attributes', $catId ),
891 * // Time-to-live (in seconds)
892 * $cache::TTL_MINUTE,
893 * // Function that derives the new key value
894 * function ( $oldValue, &$ttl, array &$setOpts ) {
895 * $dbr = wfGetDB( DB_REPLICA );
896 * // Account for any snapshot/replica DB lag
897 * $setOpts += Database::getCacheSetOptions( $dbr );
899 * return $dbr->selectRow( ... );
904 * Example usage (key that is expensive and hot):
906 * $catConfig = $cache->getWithSetCallback(
907 * // Key to store the cached value under
908 * $cache->makeKey( 'site-cat-config' ),
909 * // Time-to-live (in seconds)
911 * // Function that derives the new key value
912 * function ( $oldValue, &$ttl, array &$setOpts ) {
913 * $dbr = wfGetDB( DB_REPLICA );
914 * // Account for any snapshot/replica DB lag
915 * $setOpts += Database::getCacheSetOptions( $dbr );
917 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
920 * // Calling touchCheckKey() on this key invalidates the cache
921 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
922 * // Try to only let one datacenter thread manage cache updates at a time
924 * // Avoid querying cache servers multiple times in a web request
925 * 'pcTTL' => $cache::TTL_PROC_LONG
930 * Example usage (key with dynamic dependencies):
932 * $catState = $cache->getWithSetCallback(
933 * // Key to store the cached value under
934 * $cache->makeKey( 'cat-state', $cat->getId() ),
935 * // Time-to-live (seconds)
937 * // Function that derives the new key value
938 * function ( $oldValue, &$ttl, array &$setOpts ) {
939 * // Determine new value from the DB
940 * $dbr = wfGetDB( DB_REPLICA );
941 * // Account for any snapshot/replica DB lag
942 * $setOpts += Database::getCacheSetOptions( $dbr );
944 * return CatState::newFromResults( $dbr->select( ... ) );
947 * // The "check" keys that represent things the value depends on;
948 * // Calling touchCheckKey() on any of them invalidates the cache
950 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
951 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
952 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
958 * Example usage (key that is expensive with too many DB dependencies for "check keys"):
960 * $catToys = $cache->getWithSetCallback(
961 * // Key to store the cached value under
962 * $cache->makeKey( 'cat-toys', $catId ),
963 * // Time-to-live (seconds)
965 * // Function that derives the new key value
966 * function ( $oldValue, &$ttl, array &$setOpts ) {
967 * // Determine new value from the DB
968 * $dbr = wfGetDB( DB_REPLICA );
969 * // Account for any snapshot/replica DB lag
970 * $setOpts += Database::getCacheSetOptions( $dbr );
972 * return CatToys::newFromResults( $dbr->select( ... ) );
975 * // Get the highest timestamp of any of the cat's toys
976 * 'touchedCallback' => function ( $value ) use ( $catId ) {
977 * $dbr = wfGetDB( DB_REPLICA );
978 * $ts = $dbr->selectField( 'cat_toys', 'MAX(ct_touched)', ... );
980 * return wfTimestampOrNull( TS_UNIX, $ts );
982 * // Avoid DB queries for repeated access
983 * 'pcTTL' => $cache::TTL_PROC_SHORT
988 * Example usage (hot key holding most recent 100 events):
990 * $lastCatActions = $cache->getWithSetCallback(
991 * // Key to store the cached value under
992 * $cache->makeKey( 'cat-last-actions', 100 ),
993 * // Time-to-live (in seconds)
995 * // Function that derives the new key value
996 * function ( $oldValue, &$ttl, array &$setOpts ) {
997 * $dbr = wfGetDB( DB_REPLICA );
998 * // Account for any snapshot/replica DB lag
999 * $setOpts += Database::getCacheSetOptions( $dbr );
1001 * // Start off with the last cached list
1002 * $list = $oldValue ?: [];
1003 * // Fetch the last 100 relevant rows in descending order;
1004 * // only fetch rows newer than $list[0] to reduce scanning
1005 * $rows = iterator_to_array( $dbr->select( ... ) );
1006 * // Merge them and get the new "last 100" rows
1007 * return array_slice( array_merge( $new, $list ), 0, 100 );
1010 * // Try to only let one datacenter thread manage cache updates at a time
1012 * // Use a magic value when no cache value is ready rather than stampeding
1013 * 'busyValue' => 'computing'
1018 * Example usage (key holding an LRU subkey:value map; this can avoid flooding cache with
1019 * keys for an unlimited set of (constraint,situation) pairs, thereby avoiding elevated
1020 * cache evictions and wasted memory):
1022 * $catSituationTolerabilityCache = $this->cache->getWithSetCallback(
1023 * // Group by constraint ID/hash, cat family ID/hash, or something else useful
1024 * $this->cache->makeKey( 'cat-situation-tolerability-checks', $groupKey ),
1025 * WANObjectCache::TTL_DAY, // rarely used groups should fade away
1026 * // The $scenarioKey format is $constraintId:<ID/hash of $situation>
1027 * function ( $cacheMap ) use ( $scenarioKey, $constraintId, $situation ) {
1028 * $lruCache = MapCacheLRU::newFromArray( $cacheMap ?: [], self::CACHE_SIZE );
1029 * $result = $lruCache->get( $scenarioKey ); // triggers LRU bump if present
1030 * if ( $result === null || $this->isScenarioResultExpired( $result ) ) {
1031 * $result = $this->checkScenarioTolerability( $constraintId, $situation );
1032 * $lruCache->set( $scenarioKey, $result, 3 / 8 );
1034 * // Save the new LRU cache map and reset the map's TTL
1035 * return $lruCache->toArray();
1038 * // Once map is > 1 sec old, consider refreshing
1040 * // Update within 5 seconds after "ageNew" given a 1hz cache check rate
1042 * // Avoid querying cache servers multiple times in a request; this also means
1043 * // that a request can only alter the value of any given constraint key once
1044 * 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1047 * $tolerability = isset( $catSituationTolerabilityCache[$scenarioKey] )
1048 * ? $catSituationTolerabilityCache[$scenarioKey]
1049 * : $this->checkScenarioTolerability( $constraintId, $situation );
1052 * @see WANObjectCache::get()
1053 * @see WANObjectCache::set()
1055 * @param string $key Cache key made from makeKey() or makeGlobalKey()
1056 * @param int $ttl Seconds to live for key updates. Special values are:
1057 * - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
1058 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
1059 * @param callable $callback Value generation function
1060 * @param array $opts Options map:
1061 * - checkKeys: List of "check" keys. The key at $key will be seen as stale when either
1062 * touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This
1063 * is useful if thousands or millions of keys depend on the same entity. The entity can
1064 * simply have its "check" key updated whenever the entity is modified.
1066 * - graceTTL: If the key is invalidated (by "checkKeys"/"touchedCallback") less than this
1067 * many seconds ago, consider reusing the stale value. The odds of a refresh becomes
1068 * more likely over time, becoming certain once the grace period is reached. This can
1069 * reduce traffic spikes when millions of keys are compared to the same "check" key and
1070 * touchCheckKey() or resetCheckKey() is called on that "check" key. This option is not
1071 * useful for avoiding traffic spikes in the case of the key simply expiring on account
1072 * of its TTL (use "lowTTL" instead).
1073 * Default: WANObjectCache::GRACE_TTL_NONE.
1074 * - lockTSE: If the key is tombstoned or invalidated (by "checkKeys"/"touchedCallback")
1075 * less than this many seconds ago, try to have a single thread handle cache regeneration
1076 * at any given time. Other threads will use stale values if possible. If, on miss,
1077 * the time since expiration is low, the assumption is that the key is hot and that a
1078 * stampede is worth avoiding. Note that if the key falls out of cache then concurrent
1079 * threads will all run the callback on cache miss until the value is saved in cache.
1080 * The only stampede protection in that case is from duplicate cache sets when the
1081 * callback takes longer than WANObjectCache::SET_DELAY_HIGH_SEC seconds; consider
1082 * using "busyValue" if such stampedes are a problem. Note that the higher "lockTSE" is
1083 * set, the higher the worst-case staleness of returned values can be. Also note that
1084 * this option does not by itself handle the case of the key simply expiring on account
1085 * of its TTL, so make sure that "lowTTL" is not disabled when using this option. Avoid
1086 * combining this option with delete() as it can always cause a stampede due to their
1087 * being no stale value available until after a thread completes the callback.
1088 * Use WANObjectCache::TSE_NONE to disable this logic.
1089 * Default: WANObjectCache::TSE_NONE.
1090 * - busyValue: If no value exists and another thread is currently regenerating it, use this
1091 * as a fallback value (or a callback to generate such a value). This assures that cache
1092 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
1093 * against cache regeneration becoming very slow for some reason (greater than the TTL).
1095 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
1096 * network I/O when a key is read several times. This will not cache when the callback
1097 * returns false, however. Note that any purges will not be seen while process cached;
1098 * since the callback should use replica DBs and they may be lagged or have snapshot
1099 * isolation anyway, this should not typically matter.
1100 * Default: WANObjectCache::TTL_UNCACHEABLE.
1101 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
1102 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
1103 * large values, small yet numerous values, or some values with a high cost of eviction.
1104 * It is generally preferable to use a class constant when setting this value.
1105 * This has no effect unless pcTTL is used.
1106 * Default: WANObjectCache::PC_PRIMARY.
1107 * - version: Integer version number. This allows for callers to make breaking changes to
1108 * how values are stored while maintaining compatability and correct cache purges. New
1109 * versions are stored alongside older versions concurrently. Avoid storing class objects
1110 * however, as this reduces compatibility (due to serialization).
1112 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
1113 * This is useful if the source of a key is suspected of having possibly changed
1114 * recently, and the caller wants any such changes to be reflected.
1115 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
1116 * - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per
1117 * second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this
1118 * TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old.
1119 * This uses randomization to avoid triggering cache stampedes. The TTR is useful at
1120 * reducing the impact of missed cache purges, since the effect of a heavily referenced
1121 * key being stale is worse than that of a rarely referenced key. Unlike simply lowering
1122 * $ttl, seldomly used keys are largely unaffected by this option, which makes it
1123 * possible to have a high hit rate for the "long-tail" of less-used keys.
1124 * Default: WANObjectCache::HOT_TTR.
1125 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
1126 * than this. It becomes more likely over time, becoming certain once the key is expired.
1127 * This helps avoid cache stampedes that might be triggered due to the key expiring.
1128 * Default: WANObjectCache::LOW_TTL.
1129 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
1130 * Default: WANObjectCache::AGE_NEW.
1131 * - staleTTL: Seconds to keep the key around if it is stale. This means that on cache
1132 * miss the callback may get $oldValue/$oldAsOf values for keys that have already been
1133 * expired for this specified time. This is useful if adaptiveTTL() is used on the old
1134 * value's as-of time when it is verified as still being correct.
1135 * Default: WANObjectCache::STALE_TTL_NONE
1136 * - touchedCallback: A callback that takes the current value and returns a UNIX timestamp
1137 * indicating the last time a dynamic dependency changed. Null can be returned if there
1138 * are no relevant dependency changes to check. This can be used to check against things
1139 * like last-modified times of files or DB timestamp fields. This should generally not be
1140 * used for small and easily queried values in a DB if the callback itself ends up doing
1141 * a similarly expensive DB query to check a timestamp. Usages of this option makes the
1142 * most sense for values that are moderately to highly expensive to regenerate and easy
1143 * to query for dependency timestamps. The use of "pcTTL" reduces timestamp queries.
1145 * @return mixed Value found or written to the key
1146 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
1147 * @note Options added in 1.31: staleTTL, graceTTL
1148 * @note Options added in 1.33: touchedCallback
1149 * @note Callable type hints are not used to avoid class-autoloading
1151 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
1152 $pcTTL = $opts['pcTTL'] ?? self
::TTL_UNCACHEABLE
;
1154 // Try the process cache if enabled and the cache callback is not within a cache callback.
1155 // Process cache use in nested callbacks is not lag-safe with regard to HOLDOFF_TTL since
1156 // the in-memory value is further lagged than the shared one since it uses a blind TTL.
1157 if ( $pcTTL >= 0 && $this->callbackDepth
== 0 ) {
1158 $group = $opts['pcGroup'] ?? self
::PC_PRIMARY
;
1159 $procCache = $this->getProcessCache( $group );
1160 $value = $procCache->has( $key, $pcTTL ) ?
$procCache->get( $key ) : false;
1166 if ( $value === false ) {
1167 // Fetch the value over the network
1168 if ( isset( $opts['version'] ) ) {
1169 $version = $opts['version'];
1171 $cur = $this->doGetWithSetCallback(
1174 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1175 use ( $callback, $version ) {
1176 if ( is_array( $oldValue )
1177 && array_key_exists( self
::VFLD_DATA
, $oldValue )
1178 && array_key_exists( self
::VFLD_VERSION
, $oldValue )
1179 && $oldValue[self
::VFLD_VERSION
] === $version
1181 $oldData = $oldValue[self
::VFLD_DATA
];
1183 // VFLD_DATA is not set if an old, unversioned, key is present
1189 self
::VFLD_DATA
=> $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
1190 self
::VFLD_VERSION
=> $version
1196 if ( $cur[self
::VFLD_VERSION
] === $version ) {
1197 // Value created or existed before with version; use it
1198 $value = $cur[self
::VFLD_DATA
];
1200 // Value existed before with a different version; use variant key.
1201 // Reflect purges to $key by requiring that this key value be newer.
1202 $value = $this->doGetWithSetCallback(
1203 $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), $version ),
1206 // Regenerate value if not newer than $key
1207 [ 'version' => null, 'minAsOf' => $asOf ] +
$opts
1211 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
1214 // Update the process cache if enabled
1215 if ( $procCache && $value !== false ) {
1216 $procCache->set( $key, $value );
1224 * Do the actual I/O for getWithSetCallback() when needed
1226 * @see WANObjectCache::getWithSetCallback()
1228 * @param string $key
1230 * @param callable $callback
1231 * @param array $opts Options map for getWithSetCallback()
1232 * @param float|null &$asOf Cache generation timestamp of returned value [returned]
1234 * @note Callable type hints are not used to avoid class-autoloading
1236 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
1237 $lowTTL = $opts['lowTTL'] ??
min( self
::LOW_TTL
, $ttl );
1238 $lockTSE = $opts['lockTSE'] ?? self
::TSE_NONE
;
1239 $staleTTL = $opts['staleTTL'] ?? self
::STALE_TTL_NONE
;
1240 $graceTTL = $opts['graceTTL'] ?? self
::GRACE_TTL_NONE
;
1241 $checkKeys = $opts['checkKeys'] ??
[];
1242 $busyValue = $opts['busyValue'] ??
null;
1243 $popWindow = $opts['hotTTR'] ?? self
::HOT_TTR
;
1244 $ageNew = $opts['ageNew'] ?? self
::AGE_NEW
;
1245 $minTime = $opts['minAsOf'] ?? self
::MIN_TIMESTAMP_NONE
;
1246 $versioned = isset( $opts['version'] );
1247 $touchedCallback = $opts['touchedCallback'] ??
null;
1248 $initialTime = $this->getCurrentTime();
1250 // Get a collection name to describe this class of key
1251 $kClass = $this->determineKeyClass( $key );
1253 // Get the current key value and populate $curTTL and $asOf accordingly
1255 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
1256 $value = $cValue; // return value
1257 // Apply additional dynamic expiration logic if supplied
1258 $curTTL = $this->applyTouchedCallback( $value, $asOf, $curTTL, $touchedCallback );
1260 // Determine if a cached value regeneration is needed or desired
1262 $this->isValid( $value, $versioned, $asOf, $minTime ) &&
1263 $this->isAliveOrInGracePeriod( $curTTL, $graceTTL )
1265 $preemptiveRefresh = (
1266 $this->worthRefreshExpiring( $curTTL, $lowTTL ) ||
1267 $this->worthRefreshPopular( $asOf, $ageNew, $popWindow, $initialTime )
1270 if ( !$preemptiveRefresh ) {
1271 $this->stats
->increment( "wanobjectcache.$kClass.hit.good" );
1274 } elseif ( $this->scheduleAsyncRefresh( $key, $ttl, $callback, $opts ) ) {
1275 $this->stats
->increment( "wanobjectcache.$kClass.hit.refresh" );
1281 // Only a tombstoned key yields no value yet has a (negative) "current time left"
1282 $isKeyTombstoned = ( $curTTL !== null && $value === false );
1283 // Decide if only one thread should handle regeneration at a time
1285 // Note that since tombstones no-op set(), $lockTSE and $curTTL cannot be used to
1286 // deduce the key hotness because |$curTTL| will always keep increasing until the
1287 // tombstone expires or is overwritten by a new tombstone. Also, even if $lockTSE
1288 // is not set, constant regeneration of a key for the tombstone lifetime might be
1289 // very expensive. Assume tombstoned keys are possibly hot in order to reduce
1290 // the risk of high regeneration load after the delete() method is called.
1292 // Assume a key is hot if requested soon ($lockTSE seconds) after invalidation.
1293 // This avoids stampedes when timestamps from $checkKeys/$touchedCallback bump.
1294 ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE ) ||
1295 // Assume a key is hot if there is no value and a busy fallback is given.
1296 // This avoids stampedes on eviction or preemptive regeneration taking too long.
1297 ( $busyValue !== null && $value === false );
1301 // Acquire a datacenter-local non-blocking lock
1302 if ( $this->cache
->add( self
::MUTEX_KEY_PREFIX
. $key, 1, self
::LOCK_TTL
) ) {
1303 // Lock acquired; this thread will recompute the value and update cache
1305 } elseif ( $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1306 // Lock not acquired and a stale value exists; use the stale value
1307 $this->stats
->increment( "wanobjectcache.$kClass.hit.stale" );
1311 // Lock not acquired and no stale value exists
1312 if ( $isKeyTombstoned ) {
1313 // Use the INTERIM value from the last thread that regenerated it if possible
1314 $value = $this->getInterimValue( $key, $versioned, $minTime, $asOf );
1315 if ( $value !== false ) {
1316 $this->stats
->increment( "wanobjectcache.$kClass.hit.volatile" );
1322 if ( $busyValue !== null ) {
1323 // Use the busy fallback value if nothing else
1324 $miss = is_infinite( $minTime ) ?
'renew' : 'miss';
1325 $this->stats
->increment( "wanobjectcache.$kClass.$miss.busy" );
1327 return is_callable( $busyValue ) ?
$busyValue() : $busyValue;
1332 if ( !is_callable( $callback ) ) {
1333 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
1336 $preCallbackTime = $this->getCurrentTime();
1337 // Generate the new value from the callback...
1339 ++
$this->callbackDepth
;
1341 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
1343 --$this->callbackDepth
;
1345 $valueIsCacheable = ( $value !== false && $ttl >= 0 );
1347 if ( $valueIsCacheable ) {
1348 $ago = max( $this->getCurrentTime() - $initialTime, 0.0 );
1349 $this->stats
->timing( "wanobjectcache.$kClass.regen_set_delay", 1000 * $ago );
1351 if ( $isKeyTombstoned ) {
1352 if ( $this->checkAndSetCooloff( $key, $kClass, $ago, $lockTSE, $hasLock ) ) {
1353 // When delete() is called, writes are write-holed by the tombstone,
1354 // so use a special INTERIM key to pass the new value among threads.
1355 $tempTTL = max( self
::INTERIM_KEY_TTL
, (int)$lockTSE ); // set() expects seconds
1356 $newAsOf = $this->getCurrentTime();
1357 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
1358 // Avoid using set() to avoid pointless mcrouter broadcasting
1359 $this->setInterimValue( $key, $wrapped, $tempTTL );
1361 } elseif ( !$useMutex ||
$hasLock ) {
1362 if ( $this->checkAndSetCooloff( $key, $kClass, $ago, $lockTSE, $hasLock ) ) {
1363 // Save the value unless a lock-winning thread is already expected to do that
1364 $setOpts['lockTSE'] = $lockTSE;
1365 $setOpts['staleTTL'] = $staleTTL;
1366 // Use best known "since" timestamp if not provided
1367 $setOpts +
= [ 'since' => $preCallbackTime ];
1368 // Update the cache; this will fail if the key is tombstoned
1369 $this->set( $key, $value, $ttl, $setOpts );
1375 // Avoid using delete() to avoid pointless mcrouter broadcasting
1376 $this->cache
->changeTTL( self
::MUTEX_KEY_PREFIX
. $key, (int)$initialTime - 60 );
1379 $miss = is_infinite( $minTime ) ?
'renew' : 'miss';
1380 $this->stats
->increment( "wanobjectcache.$kClass.$miss.compute" );
1386 * @param string $key
1387 * @param string $kClass
1388 * @param float $elapsed Seconds spent regenerating the value
1389 * @param float $lockTSE
1390 * @param $hasLock bool
1391 * @return bool Whether it is OK to proceed with a key set operation
1393 private function checkAndSetCooloff( $key, $kClass, $elapsed, $lockTSE, $hasLock ) {
1394 // If $lockTSE is set, the lock was bypassed because there was no stale/interim value,
1395 // and $elapsed indicates that regeration is slow, then there is a risk of set()
1396 // stampedes with large blobs. With a typical scale-out infrastructure, CPU and query
1397 // load from $callback invocations is distributed among appservers and replica DBs,
1398 // but cache operations for a given key route to a single cache server (e.g. striped
1399 // consistent hashing).
1400 if ( $lockTSE < 0 ||
$hasLock ) {
1401 return true; // either not a priori hot or thread has the lock
1402 } elseif ( $elapsed <= self
::SET_DELAY_HIGH_SEC
) {
1403 return true; // not enough time for threads to pile up
1406 $this->cache
->clearLastError();
1408 !$this->cache
->add( self
::COOLOFF_KEY_PREFIX
. $key, 1, self
::COOLOFF_TTL
) &&
1409 // Don't treat failures due to I/O errors as the key being in cooloff
1410 $this->cache
->getLastError() === BagOStuff
::ERR_NONE
1412 $this->stats
->increment( "wanobjectcache.$kClass.cooloff_bounce" );
1421 * @param mixed $value
1422 * @param float $asOf
1423 * @param float $curTTL
1424 * @param callable|null $callback
1427 protected function applyTouchedCallback( $value, $asOf, $curTTL, $callback ) {
1428 if ( $callback === null ) {
1432 if ( !is_callable( $callback ) ) {
1433 throw new InvalidArgumentException( "Invalid expiration callback provided." );
1436 if ( $value !== false ) {
1437 $touched = $callback( $value );
1438 if ( $touched !== null && $touched >= $asOf ) {
1439 $curTTL = min( $curTTL, self
::TINY_NEGATIVE
, $asOf - $touched );
1447 * @param string $key
1448 * @param bool $versioned
1449 * @param float $minTime
1450 * @param mixed &$asOf
1453 protected function getInterimValue( $key, $versioned, $minTime, &$asOf ) {
1454 if ( !$this->useInterimHoldOffCaching
) {
1455 return false; // disabled
1458 $wrapped = $this->cache
->get( self
::INTERIM_KEY_PREFIX
. $key );
1459 list( $value ) = $this->unwrap( $wrapped, $this->getCurrentTime() );
1460 if ( $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1461 $asOf = $wrapped[self
::FLD_TIME
];
1470 * @param string $key
1471 * @param array $wrapped
1472 * @param int $tempTTL
1474 protected function setInterimValue( $key, $wrapped, $tempTTL ) {
1475 $this->cache
->merge(
1476 self
::INTERIM_KEY_PREFIX
. $key,
1477 function () use ( $wrapped ) {
1486 * Method to fetch multiple cache keys at once with regeneration
1488 * This works the same as getWithSetCallback() except:
1489 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1490 * - b) The $callback argument expects a callback taking the following arguments:
1491 * - $id: ID of an entity to query
1492 * - $oldValue : the prior cache value or false if none was present
1493 * - &$ttl : a reference to the new value TTL in seconds
1494 * - &$setOpts : a reference to options for set() which can be altered
1495 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present
1496 * Aside from the additional $id argument, the other arguments function the same
1497 * way they do in getWithSetCallback().
1498 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1500 * @see WANObjectCache::getWithSetCallback()
1501 * @see WANObjectCache::getMultiWithUnionSetCallback()
1505 * $rows = $cache->getMultiWithSetCallback(
1506 * // Map of cache keys to entity IDs
1507 * $cache->makeMultiKeys(
1508 * $this->fileVersionIds(),
1509 * function ( $id, WANObjectCache $cache ) {
1510 * return $cache->makeKey( 'file-version', $id );
1513 * // Time-to-live (in seconds)
1515 * // Function that derives the new key value
1516 * function ( $id, $oldValue, &$ttl, array &$setOpts ) {
1517 * $dbr = wfGetDB( DB_REPLICA );
1518 * // Account for any snapshot/replica DB lag
1519 * $setOpts += Database::getCacheSetOptions( $dbr );
1521 * // Load the row for this file
1522 * $queryInfo = File::getQueryInfo();
1523 * $row = $dbr->selectRow(
1524 * $queryInfo['tables'],
1525 * $queryInfo['fields'],
1529 * $queryInfo['joins']
1532 * return $row ? (array)$row : false;
1535 * // Process cache for 30 seconds
1537 * // Use a dedicated 500 item cache (initialized on-the-fly)
1538 * 'pcGroup' => 'file-versions:500'
1541 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1544 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1545 * @param int $ttl Seconds to live for key updates
1546 * @param callable $callback Callback the yields entity regeneration callbacks
1547 * @param array $opts Options map
1548 * @return array Map of (cache key => value) in the same order as $keyedIds
1551 final public function getMultiWithSetCallback(
1552 ArrayIterator
$keyedIds, $ttl, callable
$callback, array $opts = []
1554 $valueKeys = array_keys( $keyedIds->getArrayCopy() );
1555 $checkKeys = $opts['checkKeys'] ??
[];
1556 $pcTTL = $opts['pcTTL'] ?? self
::TTL_UNCACHEABLE
;
1558 // Load required keys into process cache in one go
1559 $this->warmupCache
= $this->getRawKeysForWarmup(
1560 $this->getNonProcessCachedKeys( $valueKeys, $opts, $pcTTL ),
1563 $this->warmupKeyMisses
= 0;
1565 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1566 $id = null; // current entity ID
1567 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf ) use ( $callback, &$id ) {
1568 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1572 foreach ( $keyedIds as $key => $id ) { // preserve order
1573 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1576 $this->warmupCache
= [];
1582 * Method to fetch/regenerate multiple cache keys at once
1584 * This works the same as getWithSetCallback() except:
1585 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1586 * - b) The $callback argument expects a callback returning a map of (ID => new value)
1587 * for all entity IDs in $ids and it takes the following arguments:
1588 * - $ids: a list of entity IDs that require cache regeneration
1589 * - &$ttls: a reference to the (entity ID => new TTL) map
1590 * - &$setOpts: a reference to options for set() which can be altered
1591 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1592 * - d) The "lockTSE" and "busyValue" options are ignored
1594 * @see WANObjectCache::getWithSetCallback()
1595 * @see WANObjectCache::getMultiWithSetCallback()
1599 * $rows = $cache->getMultiWithUnionSetCallback(
1600 * // Map of cache keys to entity IDs
1601 * $cache->makeMultiKeys(
1602 * $this->fileVersionIds(),
1603 * function ( $id, WANObjectCache $cache ) {
1604 * return $cache->makeKey( 'file-version', $id );
1607 * // Time-to-live (in seconds)
1609 * // Function that derives the new key value
1610 * function ( array $ids, array &$ttls, array &$setOpts ) {
1611 * $dbr = wfGetDB( DB_REPLICA );
1612 * // Account for any snapshot/replica DB lag
1613 * $setOpts += Database::getCacheSetOptions( $dbr );
1615 * // Load the rows for these files
1617 * $queryInfo = File::getQueryInfo();
1618 * $res = $dbr->select(
1619 * $queryInfo['tables'],
1620 * $queryInfo['fields'],
1624 * $queryInfo['joins']
1626 * foreach ( $res as $row ) {
1627 * $rows[$row->id] = $row;
1628 * $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
1629 * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
1636 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1639 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1640 * @param int $ttl Seconds to live for key updates
1641 * @param callable $callback Callback the yields entity regeneration callbacks
1642 * @param array $opts Options map
1643 * @return array Map of (cache key => value) in the same order as $keyedIds
1646 final public function getMultiWithUnionSetCallback(
1647 ArrayIterator
$keyedIds, $ttl, callable
$callback, array $opts = []
1649 $idsByValueKey = $keyedIds->getArrayCopy();
1650 $valueKeys = array_keys( $idsByValueKey );
1651 $checkKeys = $opts['checkKeys'] ??
[];
1652 $pcTTL = $opts['pcTTL'] ?? self
::TTL_UNCACHEABLE
;
1653 unset( $opts['lockTSE'] ); // incompatible
1654 unset( $opts['busyValue'] ); // incompatible
1656 // Load required keys into process cache in one go
1657 $keysGet = $this->getNonProcessCachedKeys( $valueKeys, $opts, $pcTTL );
1658 $this->warmupCache
= $this->getRawKeysForWarmup( $keysGet, $checkKeys );
1659 $this->warmupKeyMisses
= 0;
1661 // IDs of entities known to be in need of regeneration
1664 // Find out which keys are missing/deleted/stale
1667 $curByKey = $this->getMulti( $keysGet, $curTTLs, $checkKeys, $asOfs );
1668 foreach ( $keysGet as $key ) {
1669 if ( !array_key_exists( $key, $curByKey ) ||
$curTTLs[$key] < 0 ) {
1670 $idsRegen[] = $idsByValueKey[$key];
1674 // Run the callback to populate the regeneration value map for all required IDs
1676 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
1677 $newValsById = $idsRegen ?
$callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
1679 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1680 $id = null; // current entity ID
1681 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1682 use ( $callback, &$id, $newValsById, $newTTLsById, $newSetOpts )
1684 if ( array_key_exists( $id, $newValsById ) ) {
1685 // Value was already regerated as expected, so use the value in $newValsById
1686 $newValue = $newValsById[$id];
1687 $ttl = $newTTLsById[$id];
1688 $setOpts = $newSetOpts;
1690 // Pre-emptive/popularity refresh and version mismatch cases are not detected
1691 // above and thus $newValsById has no entry. Run $callback on this single entity.
1692 $ttls = [ $id => $ttl ];
1693 $newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
1700 // Run the cache-aside logic using warmupCache instead of persistent cache queries
1702 foreach ( $idsByValueKey as $key => $id ) { // preserve order
1703 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1706 $this->warmupCache
= [];
1712 * Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1714 * This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids
1715 * broadcasting in mcrouter setups and also avoids races with new tombstones.
1717 * @param string $key Cache key
1718 * @param int $purgeTimestamp UNIX timestamp of purge
1719 * @param bool &$isStale Whether the key is stale
1720 * @return bool Success
1723 final public function reap( $key, $purgeTimestamp, &$isStale = false ) {
1724 $minAsOf = $purgeTimestamp + self
::HOLDOFF_TTL
;
1725 $wrapped = $this->cache
->get( self
::VALUE_KEY_PREFIX
. $key );
1726 if ( is_array( $wrapped ) && $wrapped[self
::FLD_TIME
] < $minAsOf ) {
1728 $this->logger
->warning( "Reaping stale value key '$key'." );
1729 $ttlReap = self
::HOLDOFF_TTL
; // avoids races with tombstone creation
1730 $ok = $this->cache
->changeTTL( self
::VALUE_KEY_PREFIX
. $key, $ttlReap );
1732 $this->logger
->error( "Could not complete reap of key '$key'." );
1744 * Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1746 * @param string $key Cache key
1747 * @param int $purgeTimestamp UNIX timestamp of purge
1748 * @param bool &$isStale Whether the key is stale
1749 * @return bool Success
1752 final public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
1753 $purge = $this->parsePurgeValue( $this->cache
->get( self
::TIME_KEY_PREFIX
. $key ) );
1754 if ( $purge && $purge[self
::FLD_TIME
] < $purgeTimestamp ) {
1756 $this->logger
->warning( "Reaping stale check key '$key'." );
1757 $ok = $this->cache
->changeTTL( self
::TIME_KEY_PREFIX
. $key, self
::TTL_SECOND
);
1759 $this->logger
->error( "Could not complete reap of check key '$key'." );
1771 * @see BagOStuff::makeKey()
1772 * @param string $class Key class
1773 * @param string|null $component [optional] Key component (starting with a key collection name)
1774 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1777 public function makeKey( $class, $component = null ) {
1778 return $this->cache
->makeKey( ...func_get_args() );
1782 * @see BagOStuff::makeGlobalKey()
1783 * @param string $class Key class
1784 * @param string|null $component [optional] Key component (starting with a key collection name)
1785 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1788 public function makeGlobalKey( $class, $component = null ) {
1789 return $this->cache
->makeGlobalKey( ...func_get_args() );
1793 * @param array $entities List of entity IDs
1794 * @param callable $keyFunc Callback yielding a key from (entity ID, this WANObjectCache)
1795 * @return ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
1798 final public function makeMultiKeys( array $entities, callable
$keyFunc ) {
1800 foreach ( $entities as $entity ) {
1801 $map[$keyFunc( $entity, $this )] = $entity;
1804 return new ArrayIterator( $map );
1808 * Get the "last error" registered; clearLastError() should be called manually
1809 * @return int ERR_* class constant for the "last error" registry
1811 final public function getLastError() {
1812 $code = $this->cache
->getLastError();
1814 case BagOStuff
::ERR_NONE
:
1815 return self
::ERR_NONE
;
1816 case BagOStuff
::ERR_NO_RESPONSE
:
1817 return self
::ERR_NO_RESPONSE
;
1818 case BagOStuff
::ERR_UNREACHABLE
:
1819 return self
::ERR_UNREACHABLE
;
1821 return self
::ERR_UNEXPECTED
;
1826 * Clear the "last error" registry
1828 final public function clearLastError() {
1829 $this->cache
->clearLastError();
1833 * Clear the in-process caches; useful for testing
1837 public function clearProcessCache() {
1838 $this->processCaches
= [];
1842 * Enable or disable the use of brief caching for tombstoned keys
1844 * When a key is purged via delete(), there normally is a period where caching
1845 * is hold-off limited to an extremely short time. This method will disable that
1846 * caching, forcing the callback to run for any of:
1847 * - WANObjectCache::getWithSetCallback()
1848 * - WANObjectCache::getMultiWithSetCallback()
1849 * - WANObjectCache::getMultiWithUnionSetCallback()
1851 * This is useful when both:
1852 * - a) the database used by the callback is known to be up-to-date enough
1853 * for some particular purpose (e.g. replica DB has applied transaction X)
1854 * - b) the caller needs to exploit that fact, and therefore needs to avoid the
1855 * use of inherently volatile and possibly stale interim keys
1857 * @see WANObjectCache::delete()
1858 * @param bool $enabled Whether to enable interim caching
1861 final public function useInterimHoldOffCaching( $enabled ) {
1862 $this->useInterimHoldOffCaching
= $enabled;
1866 * @param int $flag ATTR_* class constant
1867 * @return int QOS_* class constant
1870 public function getQoS( $flag ) {
1871 return $this->cache
->getQoS( $flag );
1875 * Get a TTL that is higher for objects that have not changed recently
1877 * This is useful for keys that get explicit purges and DB or purge relay
1878 * lag is a potential concern (especially how it interacts with CDN cache)
1882 * // Last-modified time of page
1883 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1884 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1885 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1886 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1887 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1890 * Another use case is when there are no applicable "last modified" fields in the DB,
1891 * and there are too many dependencies for explicit purges to be viable, and the rate of
1892 * change to relevant content is unstable, and it is highly valued to have the cached value
1893 * be as up-to-date as possible.
1897 * $query = "<some complex query>";
1898 * $idListFromComplexQuery = $cache->getWithSetCallback(
1899 * $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
1900 * GraphQueryClass::STARTING_TTL,
1901 * function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
1902 * $gdb = $this->getReplicaGraphDbConnection();
1903 * // Account for any snapshot/replica DB lag
1904 * $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
1906 * $newList = iterator_to_array( $gdb->query( $query ) );
1907 * sort( $newList, SORT_NUMERIC ); // normalize
1909 * $minTTL = GraphQueryClass::MIN_TTL;
1910 * $maxTTL = GraphQueryClass::MAX_TTL;
1911 * if ( $oldValue !== false ) {
1912 * // Note that $oldAsOf is the last time this callback ran
1913 * $ttl = ( $newList === $oldValue )
1914 * // No change: cache for 150% of the age of $oldValue
1915 * ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
1916 * // Changed: cache for 50% of the age of $oldValue
1917 * : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
1923 * // Keep stale values around for doing comparisons for TTL calculations.
1924 * // High values improve long-tail keys hit-rates, though might waste space.
1925 * 'staleTTL' => GraphQueryClass::GRACE_TTL
1930 * @param int|float $mtime UNIX timestamp
1931 * @param int $maxTTL Maximum TTL (seconds)
1932 * @param int $minTTL Minimum TTL (seconds); Default: 30
1933 * @param float $factor Value in the range (0,1); Default: .2
1934 * @return int Adaptive TTL
1937 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
1938 if ( is_float( $mtime ) ||
ctype_digit( $mtime ) ) {
1939 $mtime = (int)$mtime; // handle fractional seconds and string integers
1942 if ( !is_int( $mtime ) ||
$mtime <= 0 ) {
1943 return $minTTL; // no last-modified time provided
1946 $age = $this->getCurrentTime() - $mtime;
1948 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1952 * @return int Number of warmup key cache misses last round
1955 final public function getWarmupKeyMisses() {
1956 return $this->warmupKeyMisses
;
1960 * Do the actual async bus purge of a key
1962 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1964 * @param string $key Cache key
1965 * @param int $ttl How long to keep the tombstone [seconds]
1966 * @param int $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1967 * @return bool Success
1969 protected function relayPurge( $key, $ttl, $holdoff ) {
1970 if ( $this->mcrouterAware
) {
1971 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
1972 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
1973 $ok = $this->cache
->set(
1974 "/*/{$this->cluster}/{$key}",
1975 $this->makePurgeValue( $this->getCurrentTime(), self
::HOLDOFF_NONE
),
1979 // This handles the mcrouter and the single-DC case
1980 $ok = $this->cache
->set(
1982 $this->makePurgeValue( $this->getCurrentTime(), self
::HOLDOFF_NONE
),
1991 * Do the actual async bus delete of a key
1993 * @param string $key Cache key
1994 * @return bool Success
1996 protected function relayDelete( $key ) {
1997 if ( $this->mcrouterAware
) {
1998 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
1999 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
2000 $ok = $this->cache
->delete( "/*/{$this->cluster}/{$key}" );
2002 // Some other proxy handles broadcasting or there is only one datacenter
2003 $ok = $this->cache
->delete( $key );
2010 * @param string $key
2012 * @param callable $callback
2013 * @param array $opts
2014 * @return bool Success
2016 private function scheduleAsyncRefresh( $key, $ttl, $callback, $opts ) {
2017 if ( !$this->asyncHandler
) {
2020 // Update the cache value later, such during post-send of an HTTP request
2021 $func = $this->asyncHandler
;
2022 $func( function () use ( $key, $ttl, $callback, $opts ) {
2023 $asOf = null; // unused
2024 $opts['minAsOf'] = INF
; // force a refresh
2025 $this->doGetWithSetCallback( $key, $ttl, $callback, $opts, $asOf );
2032 * Check if a key is fresh or in the grace window and thus due for randomized reuse
2034 * If $curTTL > 0 (e.g. not expired) this returns true. Otherwise, the chance of returning
2035 * true decrease steadily from 100% to 0% as the |$curTTL| moves from 0 to $graceTTL seconds.
2036 * This handles widely varying levels of cache access traffic.
2038 * If $curTTL <= -$graceTTL (e.g. already expired), then this returns false.
2040 * @param float $curTTL Approximate TTL left on the key if present
2041 * @param int $graceTTL Consider using stale values if $curTTL is greater than this
2044 protected function isAliveOrInGracePeriod( $curTTL, $graceTTL ) {
2045 if ( $curTTL > 0 ) {
2047 } elseif ( $graceTTL <= 0 ) {
2051 $ageStale = abs( $curTTL ); // seconds of staleness
2052 $curGTTL = ( $graceTTL - $ageStale ); // current grace-time-to-live
2053 if ( $curGTTL <= 0 ) {
2054 return false; // already out of grace period
2057 // Chance of using a stale value is the complement of the chance of refreshing it
2058 return !$this->worthRefreshExpiring( $curGTTL, $graceTTL );
2062 * Check if a key is nearing expiration and thus due for randomized regeneration
2064 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance of returning true
2065 * increases steadily from 0% to 100% as the $curTTL moves from $lowTTL to 0 seconds.
2066 * This handles widely varying levels of cache access traffic.
2068 * If $curTTL <= 0 (e.g. already expired), then this returns false.
2070 * @param float $curTTL Approximate TTL left on the key if present
2071 * @param float $lowTTL Consider a refresh when $curTTL is less than this
2074 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
2075 if ( $lowTTL <= 0 ) {
2077 } elseif ( $curTTL >= $lowTTL ) {
2079 } elseif ( $curTTL <= 0 ) {
2083 $chance = ( 1 - $curTTL / $lowTTL );
2085 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
2089 * Check if a key is due for randomized regeneration due to its popularity
2091 * This is used so that popular keys can preemptively refresh themselves for higher
2092 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
2093 * in cache with their high nominal TTL. This means popular keys keep good consistency,
2094 * whether the data changes frequently or not, and long-tail keys get to stay in cache
2095 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
2097 * @param float $asOf UNIX timestamp of the value
2098 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
2099 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
2100 * @param float $now The current UNIX timestamp
2103 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
2104 if ( $ageNew < 0 ||
$timeTillRefresh <= 0 ) {
2108 $age = $now - $asOf;
2109 $timeOld = $age - $ageNew;
2110 if ( $timeOld <= 0 ) {
2114 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
2115 // Note that the "expected # of refreshes" for the ramp-up time range is half of what it
2116 // would be if P(refresh) was at its full value during that time range.
2117 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self
::RAMPUP_TTL
/ 2, 1 );
2118 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
2119 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
2120 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
2121 $chance = 1 / ( self
::HIT_RATE_HIGH
* $refreshWindowSec );
2123 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
2124 $chance *= ( $timeOld <= self
::RAMPUP_TTL
) ?
$timeOld / self
::RAMPUP_TTL
: 1;
2126 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
2130 * Check if $value is not false, versioned (if needed), and not older than $minTime (if set)
2132 * @param array|bool $value
2133 * @param bool $versioned
2134 * @param float $asOf The time $value was generated
2135 * @param float $minTime The last time the main value was generated (0.0 if unknown)
2138 protected function isValid( $value, $versioned, $asOf, $minTime ) {
2139 if ( $value === false ) {
2141 } elseif ( $versioned && !isset( $value[self
::VFLD_VERSION
] ) ) {
2143 } elseif ( $minTime > 0 && $asOf < $minTime ) {
2151 * Do not use this method outside WANObjectCache
2153 * @param mixed $value
2154 * @param int $ttl [0=forever]
2155 * @param float $now Unix Current timestamp just before calling set()
2158 protected function wrap( $value, $ttl, $now ) {
2160 self
::FLD_VERSION
=> self
::VERSION
,
2161 self
::FLD_VALUE
=> $value,
2162 self
::FLD_TTL
=> $ttl,
2163 self
::FLD_TIME
=> $now
2168 * Do not use this method outside WANObjectCache
2170 * @param array|string|bool $wrapped
2171 * @param float $now Unix Current timestamp (preferrably pre-query)
2172 * @return array (mixed; false if absent/tombstoned/malformed, current time left)
2174 protected function unwrap( $wrapped, $now ) {
2175 // Check if the value is a tombstone
2176 $purge = $this->parsePurgeValue( $wrapped );
2177 if ( $purge !== false ) {
2178 // Purged values should always have a negative current $ttl
2179 $curTTL = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
2180 return [ false, $curTTL ];
2183 if ( !is_array( $wrapped ) // not found
2184 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
2185 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
2187 return [ false, null ];
2190 if ( $wrapped[self
::FLD_TTL
] > 0 ) {
2191 // Get the approximate time left on the key
2192 $age = $now - $wrapped[self
::FLD_TIME
];
2193 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
2195 // Key had no TTL, so the time left is unbounded
2199 if ( $wrapped[self
::FLD_TIME
] < $this->epoch
) {
2200 // Values this old are ignored
2201 return [ false, null ];
2204 return [ $wrapped[self
::FLD_VALUE
], $curTTL ];
2208 * @param array $keys
2209 * @param string $prefix
2212 protected static function prefixCacheKeys( array $keys, $prefix ) {
2214 foreach ( $keys as $key ) {
2215 $res[] = $prefix . $key;
2222 * @param string $key String of the format <scope>:<class>[:<class or variable>]...
2225 protected function determineKeyClass( $key ) {
2226 $parts = explode( ':', $key );
2228 return $parts[1] ??
$parts[0]; // sanity
2232 * @param string|array|bool $value Possible string of the form "PURGED:<timestamp>:<holdoff>"
2233 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
2234 * or false if value isn't a valid purge value
2236 protected function parsePurgeValue( $value ) {
2237 if ( !is_string( $value ) ) {
2241 $segments = explode( ':', $value, 3 );
2242 if ( !isset( $segments[0] ) ||
!isset( $segments[1] )
2243 ||
"{$segments[0]}:" !== self
::PURGE_VAL_PREFIX
2248 if ( !isset( $segments[2] ) ) {
2249 // Back-compat with old purge values without holdoff
2250 $segments[2] = self
::HOLDOFF_TTL
;
2253 if ( $segments[1] < $this->epoch
) {
2254 // Values this old are ignored
2259 self
::FLD_TIME
=> (float)$segments[1],
2260 self
::FLD_HOLDOFF
=> (int)$segments[2],
2265 * @param float $timestamp
2266 * @param int $holdoff In seconds
2267 * @return string Wrapped purge value
2269 protected function makePurgeValue( $timestamp, $holdoff ) {
2270 return self
::PURGE_VAL_PREFIX
. (float)$timestamp . ':' . (int)$holdoff;
2274 * @param string $group
2275 * @return MapCacheLRU
2277 protected function getProcessCache( $group ) {
2278 if ( !isset( $this->processCaches
[$group] ) ) {
2279 list( , $n ) = explode( ':', $group );
2280 $this->processCaches
[$group] = new MapCacheLRU( (int)$n );
2283 return $this->processCaches
[$group];
2287 * @param array $keys
2288 * @param array $opts
2290 * @return array List of keys
2292 private function getNonProcessCachedKeys( array $keys, array $opts, $pcTTL ) {
2294 if ( isset( $opts['pcTTL'] ) && $opts['pcTTL'] > 0 && $this->callbackDepth
== 0 ) {
2295 $pcGroup = $opts['pcGroup'] ?? self
::PC_PRIMARY
;
2296 $procCache = $this->getProcessCache( $pcGroup );
2297 foreach ( $keys as $key ) {
2298 if ( $procCache->has( $key, $pcTTL ) ) {
2299 $keysFound[] = $key;
2304 return array_diff( $keys, $keysFound );
2308 * @param array $keys
2309 * @param array $checkKeys
2310 * @return array Map of (cache key => mixed)
2312 private function getRawKeysForWarmup( array $keys, array $checkKeys ) {
2318 // Get all the value keys to fetch...
2319 foreach ( $keys as $key ) {
2320 $keysWarmUp[] = self
::VALUE_KEY_PREFIX
. $key;
2322 // Get all the check keys to fetch...
2323 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
2324 if ( is_int( $i ) ) {
2325 // Single check key that applies to all value keys
2326 $keysWarmUp[] = self
::TIME_KEY_PREFIX
. $checkKeyOrKeys;
2328 // List of check keys that apply to value key $i
2329 $keysWarmUp = array_merge(
2331 self
::prefixCacheKeys( $checkKeyOrKeys, self
::TIME_KEY_PREFIX
)
2336 $warmupCache = $this->cache
->getMulti( $keysWarmUp );
2337 $warmupCache +
= array_fill_keys( $keysWarmUp, false );
2339 return $warmupCache;
2343 * @return float UNIX timestamp
2344 * @codeCoverageIgnore
2346 protected function getCurrentTime() {
2347 if ( $this->wallClockOverride
) {
2348 return $this->wallClockOverride
;
2351 $clockTime = (float)time(); // call this first
2352 // microtime() uses an initial gettimeofday() call added to usage clocks.
2353 // This can severely drift from time() and the microtime() value of other threads
2354 // due to undercounting of the amount of time elapsed. Instead of seeing the current
2355 // time as being in the past, use the value of time(). This avoids setting cache values
2356 // that will immediately be seen as expired and possibly cause stampedes.
2357 return max( microtime( true ), $clockTime );
2361 * @param float|null &$time Mock UNIX timestamp for testing
2362 * @codeCoverageIgnore
2364 public function setMockTime( &$time ) {
2365 $this->wallClockOverride
=& $time;
2366 $this->cache
->setMockTime( $time );