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 * All operations go to the local datacenter cache, except for delete(),
31 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
33 * This class is intended for caching data from primary stores.
34 * If the get() method does not return a value, then the caller
35 * should query the new value and backfill the cache using set().
36 * The preferred way to do this logic is through getWithSetCallback().
37 * When querying the store on cache miss, the closest DB replica
38 * should be used. Try to avoid heavyweight DB master or quorum reads.
39 * When the source data changes, a purge method should be called.
40 * Since purges are expensive, they should be avoided. One can do so if:
41 * - a) The object cached is immutable; or
42 * - b) Validity is checked against the source after get(); or
43 * - c) Using a modest TTL is reasonably correct and performant
45 * The simplest purge method is delete().
47 * There are three supported ways to handle broadcasted operations:
48 * - a) Configure the 'purge' EventRelayer to point to a valid PubSub endpoint
49 * that has subscribed listeners on the cache servers applying the cache updates.
50 * - b) Ommit the 'purge' EventRelayer parameter and set up mcrouter as the underlying cache
51 * backend, using a memcached BagOStuff class for the 'cache' parameter. The 'region'
52 * and 'cluster' parameters must be provided and 'mcrouterAware' must be set to 'true'.
53 * Configure mcrouter as follows:
54 * - 1) Use Route Prefixing based on region (datacenter) and cache cluster.
55 * See https://github.com/facebook/mcrouter/wiki/Routing-Prefix and
56 * https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
57 * - 2) To increase the consistency of delete() and touchCheckKey() during cache
58 * server membership changes, you can use the OperationSelectorRoute to
59 * configure 'set' and 'delete' operations to go to all servers in the cache
60 * cluster, instead of just one server determined by hashing.
61 * See https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles
62 * - c) Ommit the 'purge' EventRelayer parameter and set up dynomite as cache middleware
63 * between the web servers and either memcached or redis. This will also broadcast all
64 * key setting operations, not just purges, which can be useful for cache warming.
65 * Writes are eventually consistent via the Dynamo replication model.
66 * See https://github.com/Netflix/dynomite
68 * Broadcasted operations like delete() and touchCheckKey() are done asynchronously
69 * in all datacenters this way, though the local one should likely be near immediate.
71 * This means that callers in all datacenters may see older values for however many
72 * milliseconds that the purge took to reach that datacenter. As with any cache, this
73 * should not be relied on for cases where reads are used to determine writes to source
74 * (e.g. non-cache) data stores, except when reading immutable data.
76 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
77 * to avoid collisions with keys that are not wrapped as metadata arrays. The
78 * prefixes are as follows:
79 * - a) "WANCache:v" : used for regular value keys
80 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
81 * - c) "WANCache:t" : used for storing timestamp "check" keys
82 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
87 class WANObjectCache
implements IExpiringStore
, LoggerAwareInterface
{
88 /** @var BagOStuff The local datacenter cache */
90 /** @var HashBagOStuff[] Map of group PHP instance caches */
91 protected $processCaches = [];
92 /** @var string Purge channel name */
93 protected $purgeChannel;
94 /** @var EventRelayer Bus that handles purge broadcasts */
95 protected $purgeRelayer;
96 /** @bar bool Whether to use mcrouter key prefixing for routing */
97 protected $mcrouterAware;
98 /** @var string Physical region for mcrouter use */
100 /** @var string Cache cluster name for mcrouter use */
102 /** @var LoggerInterface */
104 /** @var StatsdDataFactoryInterface */
106 /** @var bool Whether to use "interim" caching while keys are tombstoned */
107 protected $useInterimHoldOffCaching = true;
108 /** @var callable|null Function that takes a WAN cache callback and runs it later */
109 protected $asyncHandler;
111 /** @var int ERR_* constant for the "last error" registry */
112 protected $lastRelayError = self
::ERR_NONE
;
114 /** @var int Callback stack depth for getWithSetCallback() */
115 private $callbackDepth = 0;
116 /** @var mixed[] Temporary warm-up cache */
117 private $warmupCache = [];
118 /** @var int Key fetched */
119 private $warmupKeyMisses = 0;
121 /** @var float|null */
122 private $wallClockOverride;
124 /** Max time expected to pass between delete() and DB commit finishing */
125 const MAX_COMMIT_DELAY
= 3;
126 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
127 const MAX_READ_LAG
= 7;
128 /** Seconds to tombstone keys on delete() */
129 const HOLDOFF_TTL
= 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
131 /** Seconds to keep dependency purge keys around */
132 const CHECK_KEY_TTL
= self
::TTL_YEAR
;
133 /** Seconds to keep interim value keys for tombstoned keys around */
134 const INTERIM_KEY_TTL
= 1;
136 /** Seconds to keep lock keys around */
138 /** Default remaining TTL at which to consider pre-emptive regeneration */
141 /** Never consider performing "popularity" refreshes until a key reaches this age */
143 /** The time length of the "popularity" refresh window for hot keys */
145 /** Hits/second for a refresh to be expected within the "popularity" window */
146 const HIT_RATE_HIGH
= 1;
147 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
148 const RAMPUP_TTL
= 30;
150 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
151 const TTL_UNCACHEABLE
= -1;
152 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
154 /** Max TTL to store keys when a data sourced is lagged */
155 const TTL_LAGGED
= 30;
156 /** Idiom for delete() for "no hold-off" */
157 const HOLDOFF_NONE
= 0;
158 /** Idiom for set()/getWithSetCallback() for "do not augment the storage medium TTL" */
159 const STALE_TTL_NONE
= 0;
160 /** Idiom for set()/getWithSetCallback() for "no post-expired grace period" */
161 const GRACE_TTL_NONE
= 0;
163 /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
164 const MIN_TIMESTAMP_NONE
= 0.0;
166 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
167 const TINY_NEGATIVE
= -0.000001;
169 /** Cache format version number */
172 const FLD_VERSION
= 0; // key to cache version number
173 const FLD_VALUE
= 1; // key to the cached value
174 const FLD_TTL
= 2; // key to the original TTL
175 const FLD_TIME
= 3; // key to the cache time
176 const FLD_FLAGS
= 4; // key to the flags bitfield
177 const FLD_HOLDOFF
= 5; // key to any hold-off TTL
179 /** @var int Treat this value as expired-on-arrival */
182 const ERR_NONE
= 0; // no error
183 const ERR_NO_RESPONSE
= 1; // no response
184 const ERR_UNREACHABLE
= 2; // can't connect
185 const ERR_UNEXPECTED
= 3; // response gave some error
186 const ERR_RELAY
= 4; // relay broadcast failed
188 const VALUE_KEY_PREFIX
= 'WANCache:v:';
189 const INTERIM_KEY_PREFIX
= 'WANCache:i:';
190 const TIME_KEY_PREFIX
= 'WANCache:t:';
191 const MUTEX_KEY_PREFIX
= 'WANCache:m:';
193 const PURGE_VAL_PREFIX
= 'PURGED:';
195 const VFLD_DATA
= 'WOC:d'; // key to the value of versioned data
196 const VFLD_VERSION
= 'WOC:v'; // key to the version of the value present
198 const PC_PRIMARY
= 'primary:1000'; // process cache name and max key count
200 const DEFAULT_PURGE_CHANNEL
= 'wancache-purge';
203 * @param array $params
204 * - cache : BagOStuff object for a persistent cache
205 * - channels : Map of (action => channel string). Actions include "purge".
206 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
207 * - logger : LoggerInterface object
208 * - stats : LoggerInterface object
209 * - asyncHandler : A function that takes a callback and runs it later. If supplied,
210 * whenever a preemptive refresh would be triggered in getWithSetCallback(), the
211 * current cache value is still used instead. However, the async-handler function
212 * receives a WAN cache callback that, when run, will execute the value generation
213 * callback supplied by the getWithSetCallback() caller. The result will be saved
214 * as normal. The handler is expected to call the WAN cache callback at an opportune
215 * time (e.g. HTTP post-send), though generally within a few 100ms. [optional]
216 * - region: the current physical region. This is required when using mcrouter as the
217 * backing store proxy. [optional]
218 * - cluster: name of the cache cluster used by this WAN cache. The name must be the
219 * same in all datacenters; the ("region","cluster") tuple is what distinguishes
220 * the counterpart cache clusters among all the datacenter. The contents of
221 * https://github.com/facebook/mcrouter/wiki/Config-Files give background on this.
222 * This is required when using mcrouter as the backing store proxy. [optional]
223 * - mcrouterAware: set as true if mcrouter is the backing store proxy and mcrouter
224 * is configured to interpret /<region>/<cluster>/ key prefixes as routes. This
225 * requires that "region" and "cluster" are both set above. [optional]
227 public function __construct( array $params ) {
228 $this->cache
= $params['cache'];
229 $this->purgeChannel
= $params['channels']['purge'] ?? self
::DEFAULT_PURGE_CHANNEL
;
230 $this->purgeRelayer
= $params['relayers']['purge'] ??
new EventRelayerNull( [] );
231 $this->region
= $params['region'] ??
'main';
232 $this->cluster
= $params['cluster'] ??
'wan-main';
233 $this->mcrouterAware
= !empty( $params['mcrouterAware'] );
235 $this->setLogger( $params['logger'] ??
new NullLogger() );
236 $this->stats
= $params['stats'] ??
new NullStatsdDataFactory();
237 $this->asyncHandler
= $params['asyncHandler'] ??
null;
241 * @param LoggerInterface $logger
243 public function setLogger( LoggerInterface
$logger ) {
244 $this->logger
= $logger;
248 * Get an instance that wraps EmptyBagOStuff
250 * @return WANObjectCache
252 public static function newEmpty() {
254 'cache' => new EmptyBagOStuff()
259 * Fetch the value of a key from cache
261 * If supplied, $curTTL is set to the remaining TTL (current time left):
262 * - a) INF; if $key exists, has no TTL, and is not invalidated by $checkKeys
263 * - b) float (>=0); if $key exists, has a TTL, and is not invalidated by $checkKeys
264 * - c) float (<0); if $key is tombstoned, stale, or existing but invalidated by $checkKeys
265 * - d) null; if $key does not exist and is not tombstoned
267 * If a key is tombstoned, $curTTL will reflect the time since delete().
269 * The timestamp of $key will be checked against the last-purge timestamp
270 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
271 * initialized to the current timestamp. If any of $checkKeys have a timestamp
272 * greater than that of $key, then $curTTL will reflect how long ago $key
273 * became invalid. Callers can use $curTTL to know when the value is stale.
274 * The $checkKeys parameter allow mass invalidations by updating a single key:
275 * - a) Each "check" key represents "last purged" of some source data
276 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
277 * - c) When the source data that "check" keys represent changes,
278 * the touchCheckKey() method is called on them
280 * Source data entities might exists in a DB that uses snapshot isolation
281 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
282 * isolation can largely be maintained by doing the following:
283 * - a) Calling delete() on entity change *and* creation, before DB commit
284 * - b) Keeping transaction duration shorter than the delete() hold-off TTL
285 * - c) Disabling interim key caching via useInterimHoldOffCaching() before get() calls
287 * However, pre-snapshot values might still be seen if an update was made
288 * in a remote datacenter but the purge from delete() didn't relay yet.
290 * Consider using getWithSetCallback() instead of get() and set() cycles.
291 * That method has cache slam avoiding features for hot/expensive keys.
293 * @param string $key Cache key made from makeKey() or makeGlobalKey()
294 * @param mixed &$curTTL Approximate TTL left on the key if present/tombstoned [returned]
295 * @param array $checkKeys List of "check" keys
296 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
297 * @return mixed Value of cache key or false on failure
299 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
302 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
303 $curTTL = $curTTLs[$key] ??
null;
304 $asOf = $asOfs[$key] ??
null;
306 return $values[$key] ??
false;
310 * Fetch the value of several keys from cache
312 * @see WANObjectCache::get()
314 * @param array $keys List of cache keys made from makeKey() or makeGlobalKey()
315 * @param array &$curTTLs Map of (key => approximate TTL left) for existing keys [returned]
316 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
317 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
318 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
319 * @return array Map of (key => value) for keys that exist and are not tombstoned
321 final public function getMulti(
322 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
328 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
329 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
331 $checkKeysForAll = [];
332 $checkKeysByKey = [];
334 foreach ( $checkKeys as $i => $checkKeyGroup ) {
335 $prefixed = self
::prefixCacheKeys( (array)$checkKeyGroup, self
::TIME_KEY_PREFIX
);
336 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
337 // Is this check keys for a specific cache key, or for all keys being fetched?
338 if ( is_int( $i ) ) {
339 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
341 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
342 ?
array_merge( $checkKeysByKey[$i], $prefixed )
347 // Fetch all of the raw values
348 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
349 if ( $this->warmupCache
) {
350 $wrappedValues = array_intersect_key( $this->warmupCache
, array_flip( $keysGet ) );
351 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) ); // keys left to fetch
352 $this->warmupKeyMisses +
= count( $keysGet );
357 $wrappedValues +
= $this->cache
->getMulti( $keysGet );
359 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
360 $now = $this->getCurrentTime();
362 // Collect timestamps from all "check" keys
363 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
364 $purgeValuesByKey = [];
365 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
366 $purgeValuesByKey[$cacheKey] =
367 $this->processCheckKeys( $checks, $wrappedValues, $now );
370 // Get the main cache value for each key and validate them
371 foreach ( $valueKeys as $vKey ) {
372 if ( !isset( $wrappedValues[$vKey] ) ) {
373 continue; // not found
376 $key = substr( $vKey, $vPrefixLen ); // unprefix
378 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
379 if ( $value !== false ) {
380 $result[$key] = $value;
381 // Force dependent keys to be seen as stale for a while after purging
382 // to reduce race conditions involving stale data getting cached
383 $purgeValues = $purgeValuesForAll;
384 if ( isset( $purgeValuesByKey[$key] ) ) {
385 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
387 foreach ( $purgeValues as $purge ) {
388 $safeTimestamp = $purge[self
::FLD_TIME
] +
$purge[self
::FLD_HOLDOFF
];
389 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
390 // How long ago this value was invalidated by *this* check key
391 $ago = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
392 // How long ago this value was invalidated by *any* known check key
393 $curTTL = min( $curTTL, $ago );
397 $curTTLs[$key] = $curTTL;
398 $asOfs[$key] = ( $value !== false ) ?
$wrappedValues[$vKey][self
::FLD_TIME
] : null;
406 * @param array $timeKeys List of prefixed time check keys
407 * @param array $wrappedValues
409 * @return array List of purge value arrays
411 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
413 foreach ( $timeKeys as $timeKey ) {
414 $purge = isset( $wrappedValues[$timeKey] )
415 ?
$this->parsePurgeValue( $wrappedValues[$timeKey] )
417 if ( $purge === false ) {
418 // Key is not set or malformed; regenerate
419 $newVal = $this->makePurgeValue( $now, self
::HOLDOFF_TTL
);
420 $this->cache
->add( $timeKey, $newVal, self
::CHECK_KEY_TTL
);
421 $purge = $this->parsePurgeValue( $newVal );
423 $purgeValues[] = $purge;
429 * Set the value of a key in cache
431 * Simply calling this method when source data changes is not valid because
432 * the changes do not replicate to the other WAN sites. In that case, delete()
433 * should be used instead. This method is intended for use on cache misses.
435 * If the data was read from a snapshot-isolated transactions (e.g. the default
436 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
438 * - b) T2 updates a row, calls delete(), and commits
439 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
440 * - d) T1 reads the row and calls set() due to a cache miss
441 * - e) Stale value is stuck in cache
443 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
445 * Be aware that this does not update the process cache for getWithSetCallback()
446 * callers. Keys accessed via that method are not generally meant to also be set
447 * using this primitive method.
449 * Do not use this method on versioned keys accessed via getWithSetCallback().
453 * $dbr = wfGetDB( DB_REPLICA );
454 * $setOpts = Database::getCacheSetOptions( $dbr );
455 * // Fetch the row from the DB
456 * $row = $dbr->selectRow( ... );
457 * $key = $cache->makeKey( 'building', $buildingId );
458 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
461 * @param string $key Cache key
462 * @param mixed $value
463 * @param int $ttl Seconds to live. Special values are:
464 * - WANObjectCache::TTL_INDEFINITE: Cache forever
465 * @param array $opts Options map:
466 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
467 * before the data was read or, if applicable, the replica DB lag before
468 * the snapshot-isolated transaction the data was read from started.
469 * Use false to indicate that replication is not running.
471 * - since : UNIX timestamp of the data in $value. Typically, this is either
472 * the current time the data was read or (if applicable) the time when
473 * the snapshot-isolated transaction the data was read from started.
475 * - pending : Whether this data is possibly from an uncommitted write transaction.
476 * Generally, other threads should not see values from the future and
477 * they certainly should not see ones that ended up getting rolled back.
479 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
480 * with this TTL and flag it as stale. This is only useful if the reads for this key
481 * use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set
482 * then it will still add on to this TTL in the excessive lag scenario.
483 * Default: WANObjectCache::TSE_NONE
484 * - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
485 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
486 * will call the regeneration callback in such cases, passing in the old value
487 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
488 * on the old value's as-of time when it is verified as still being correct.
489 * Default: WANObjectCache::STALE_TTL_NONE.
490 * @note Options added in 1.28: staleTTL
491 * @return bool Success
493 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
494 $now = $this->getCurrentTime();
495 $lockTSE = $opts['lockTSE'] ?? self
::TSE_NONE
;
496 $staleTTL = $opts['staleTTL'] ?? self
::STALE_TTL_NONE
;
497 $age = isset( $opts['since'] ) ?
max( 0, $now - $opts['since'] ) : 0;
498 $lag = $opts['lag'] ??
0;
500 // Do not cache potentially uncommitted data as it might get rolled back
501 if ( !empty( $opts['pending'] ) ) {
502 $this->logger
->info( 'Rejected set() for {cachekey} due to pending writes.',
503 [ 'cachekey' => $key ] );
505 return true; // no-op the write for being unsafe
508 $wrapExtra = []; // additional wrapped value fields
509 // Check if there's a risk of writing stale data after the purge tombstone expired
510 if ( $lag === false ||
( $lag +
$age ) > self
::MAX_READ_LAG
) {
511 // Case A: read lag with "lockTSE"; save but record value as stale
512 if ( $lockTSE >= 0 ) {
513 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
514 $wrapExtra[self
::FLD_FLAGS
] = self
::FLG_STALE
; // mark as stale
515 // Case B: any long-running transaction; ignore this set()
516 } elseif ( $age > self
::MAX_READ_LAG
) {
517 $this->logger
->info( 'Rejected set() for {cachekey} due to snapshot lag.',
518 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] );
520 return true; // no-op the write for being unsafe
521 // Case C: high replication lag; lower TTL instead of ignoring all set()s
522 } elseif ( $lag === false ||
$lag > self
::MAX_READ_LAG
) {
523 $ttl = $ttl ?
min( $ttl, self
::TTL_LAGGED
) : self
::TTL_LAGGED
;
524 $this->logger
->warning( 'Lowered set() TTL for {cachekey} due to replication lag.',
525 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] );
526 // Case D: medium length request with medium replication lag; ignore this set()
528 $this->logger
->info( 'Rejected set() for {cachekey} due to high read lag.',
529 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] );
531 return true; // no-op the write for being unsafe
535 // Wrap that value with time/TTL/version metadata
536 $wrapped = $this->wrap( $value, $ttl, $now ) +
$wrapExtra;
538 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
539 return ( is_string( $cWrapped ) )
540 ?
false // key is tombstoned; do nothing
544 return $this->cache
->merge( self
::VALUE_KEY_PREFIX
. $key, $func, $ttl +
$staleTTL, 1 );
548 * Purge a key from all datacenters
550 * This should only be called when the underlying data (being cached)
551 * changes in a significant way. This deletes the key and starts a hold-off
552 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
553 * This is done to avoid the following race condition:
554 * - a) Some DB data changes and delete() is called on a corresponding key
555 * - b) A request refills the key with a stale value from a lagged DB
556 * - c) The stale value is stuck there until the key is expired/evicted
558 * This is implemented by storing a special "tombstone" value at the cache
559 * key that this class recognizes; get() calls will return false for the key
560 * and any set() calls will refuse to replace tombstone values at the key.
561 * For this to always avoid stale value writes, the following must hold:
562 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
563 * - b) If lag is higher, the DB will have gone into read-only mode already
565 * Note that set() can also be lag-aware and lower the TTL if it's high.
567 * Be aware that this does not clear the process cache. Even if it did, callbacks
568 * used by getWithSetCallback() might still return stale data in the case of either
569 * uncommitted or not-yet-replicated changes (callback generally use replica DBs).
571 * When using potentially long-running ACID transactions, a good pattern is
572 * to use a pre-commit hook to issue the delete. This means that immediately
573 * after commit, callers will see the tombstone in cache upon purge relay.
574 * It also avoids the following race condition:
575 * - a) T1 begins, changes a row, and calls delete()
576 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
577 * - c) T2 starts, reads the row and calls set() due to a cache miss
578 * - d) T1 finally commits
579 * - e) Stale value is stuck in cache
583 * $dbw->startAtomic( __METHOD__ ); // start of request
584 * ... <execute some stuff> ...
585 * // Update the row in the DB
586 * $dbw->update( ... );
587 * $key = $cache->makeKey( 'homes', $homeId );
588 * // Purge the corresponding cache entry just before committing
589 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
590 * $cache->delete( $key );
592 * ... <execute some stuff> ...
593 * $dbw->endAtomic( __METHOD__ ); // end of request
596 * The $ttl parameter can be used when purging values that have not actually changed
597 * recently. For example, a cleanup script to purge cache entries does not really need
598 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
599 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
601 * If called twice on the same key, then the last hold-off TTL takes precedence. For
602 * idempotence, the $ttl should not vary for different delete() calls on the same key.
604 * @param string $key Cache key
605 * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
606 * @return bool True if the item was purged or not found, false on failure
608 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
609 $key = self
::VALUE_KEY_PREFIX
. $key;
612 // Publish the purge to all datacenters
613 $ok = $this->relayDelete( $key );
615 // Publish the purge to all datacenters
616 $ok = $this->relayPurge( $key, $ttl, self
::HOLDOFF_NONE
);
623 * Fetch the value of a timestamp "check" key
625 * The key will be *initialized* to the current time if not set,
626 * so only call this method if this behavior is actually desired
628 * The timestamp can be used to check whether a cached value is valid.
629 * Callers should not assume that this returns the same timestamp in
630 * all datacenters due to relay delays.
632 * The level of staleness can roughly be estimated from this key, but
633 * if the key was evicted from cache, such calculations may show the
634 * time since expiry as ~0 seconds.
636 * Note that "check" keys won't collide with other regular keys.
639 * @return float UNIX timestamp
641 final public function getCheckKeyTime( $key ) {
642 return $this->getMultiCheckKeyTime( [ $key ] )[$key];
646 * Fetch the values of each timestamp "check" key
648 * This works like getCheckKeyTime() except it takes a list of keys
649 * and returns a map of timestamps instead of just that of one key
651 * This might be useful if both:
652 * - a) a class of entities each depend on hundreds of other entities
653 * - b) these other entities are depended upon by millions of entities
655 * The later entities can each use a "check" key to invalidate their dependee entities.
656 * However, it is expensive for the former entities to verify against all of the relevant
657 * "check" keys during each getWithSetCallback() call. A less expensive approach is to do
658 * these verifications only after a "time-till-verify" (TTV) has passed. This is a middle
659 * ground between using blind TTLs and using constant verification. The adaptiveTTL() method
660 * can be used to dynamically adjust the TTV. Also, the initial TTV can make use of the
661 * last-modified times of the dependant entities (either from the DB or the "check" keys).
665 * $value = $cache->getWithSetCallback(
666 * $cache->makeGlobalKey( 'wikibase-item', $id ),
667 * self::INITIAL_TTV, // initial time-till-verify
668 * function ( $oldValue, &$ttv, &$setOpts, $oldAsOf ) use ( $checkKeys, $cache ) {
669 * $now = microtime( true );
670 * // Use $oldValue if it passes max ultimate age and "check" key comparisons
672 * $oldAsOf > max( $cache->getMultiCheckKeyTime( $checkKeys ) ) &&
673 * ( $now - $oldValue['ctime'] ) <= self::MAX_CACHE_AGE
675 * // Increase time-till-verify by 50% of last time to reduce overhead
676 * $ttv = $cache->adaptiveTTL( $oldAsOf, self::MAX_TTV, self::MIN_TTV, 1.5 );
677 * // Unlike $oldAsOf, "ctime" is the ultimate age of the cached data
681 * $mtimes = []; // dependency last-modified times; passed by reference
682 * $value = [ 'data' => $this->fetchEntityData( $mtimes ), 'ctime' => $now ];
683 * // Guess time-till-change among the dependencies, e.g. 1/(total change rate)
684 * $ttc = 1 / array_sum( array_map(
685 * function ( $mtime ) use ( $now ) {
686 * return 1 / ( $mtime ? ( $now - $mtime ) : 900 );
690 * // The time-to-verify should not be overly pessimistic nor optimistic
691 * $ttv = min( max( $ttc, self::MIN_TTV ), self::MAX_TTV );
695 * [ 'staleTTL' => $cache::TTL_DAY ] // keep around to verify and re-save
699 * @see WANObjectCache::getCheckKeyTime()
700 * @see WANObjectCache::getWithSetCallback()
703 * @return float[] Map of (key => UNIX timestamp)
706 final public function getMultiCheckKeyTime( array $keys ) {
708 foreach ( $keys as $key ) {
709 $rawKeys[$key] = self
::TIME_KEY_PREFIX
. $key;
712 $rawValues = $this->cache
->getMulti( $rawKeys );
713 $rawValues +
= array_fill_keys( $rawKeys, false );
716 foreach ( $rawKeys as $key => $rawKey ) {
717 $purge = $this->parsePurgeValue( $rawValues[$rawKey] );
718 if ( $purge !== false ) {
719 $time = $purge[self
::FLD_TIME
];
721 // Casting assures identical floats for the next getCheckKeyTime() calls
722 $now = (string)$this->getCurrentTime();
725 $this->makePurgeValue( $now, self
::HOLDOFF_TTL
),
731 $times[$key] = $time;
738 * Purge a "check" key from all datacenters, invalidating keys that use it
740 * This should only be called when the underlying data (being cached)
741 * changes in a significant way, and it is impractical to call delete()
742 * on all keys that should be changed. When get() is called on those
743 * keys, the relevant "check" keys must be supplied for this to work.
745 * The "check" key essentially represents a last-modified time of an entity.
746 * When the key is touched, the timestamp will be updated to the current time.
747 * Keys using the "check" key via get(), getMulti(), or getWithSetCallback() will
748 * be invalidated. This approach is useful if many keys depend on a single entity.
750 * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the
751 * future by get*() methods in order to avoid race conditions where keys are updated
752 * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check"
753 * key, making it possible to know the timestamp of the last change to the corresponding
754 * entities in most cases. This might use more cache space than resetCheckKey().
756 * When a few important keys get a large number of hits, a high cache time is usually
757 * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate
758 * in such cases since the "time since expiry" cannot be inferred, causing any get()
759 * after the reset to treat the key as being "hot", resulting in more stale value usage.
761 * Note that "check" keys won't collide with other regular keys.
763 * @see WANObjectCache::get()
764 * @see WANObjectCache::getWithSetCallback()
765 * @see WANObjectCache::resetCheckKey()
767 * @param string $key Cache key
768 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
769 * @return bool True if the item was purged or not found, false on failure
771 final public function touchCheckKey( $key, $holdoff = self
::HOLDOFF_TTL
) {
772 // Publish the purge to all datacenters
773 return $this->relayPurge( self
::TIME_KEY_PREFIX
. $key, self
::CHECK_KEY_TTL
, $holdoff );
777 * Delete a "check" key from all datacenters, invalidating keys that use it
779 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
780 * or getWithSetCallback() will be invalidated. The differences are:
781 * - a) The "check" key will be deleted from all caches and lazily
782 * re-initialized when accessed (rather than set everywhere)
783 * - b) Thus, dependent keys will be known to be stale, but not
784 * for how long (they are treated as "just" purged), which
785 * effects any lockTSE logic in getWithSetCallback()
786 * - c) Since "check" keys are initialized only on the server the key hashes
787 * to, any temporary ejection of that server will cause the value to be
788 * seen as purged as a new server will initialize the "check" key.
790 * The advantage here is that the "check" keys, which have high TTLs, will only
791 * be created when a get*() method actually uses that key. This is better when
792 * a large number of "check" keys are invalided in a short period of time.
794 * Note that "check" keys won't collide with other regular keys.
796 * @see WANObjectCache::get()
797 * @see WANObjectCache::getWithSetCallback()
798 * @see WANObjectCache::touchCheckKey()
800 * @param string $key Cache key
801 * @return bool True if the item was purged or not found, false on failure
803 final public function resetCheckKey( $key ) {
804 // Publish the purge to all datacenters
805 return $this->relayDelete( self
::TIME_KEY_PREFIX
. $key );
809 * Method to fetch/regenerate cache keys
811 * On cache miss, the key will be set to the callback result via set()
812 * (unless the callback returns false) and that result will be returned.
813 * The arguments supplied to the callback are:
814 * - $oldValue : current cache value or false if not present
815 * - &$ttl : a reference to the TTL which can be altered
816 * - &$setOpts : a reference to options for set() which can be altered
817 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
819 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
820 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
821 * value, but it can be used to maintain "most recent X" values that come from time or
822 * sequence based source data, provided that the "as of" id/time is tracked. Note that
823 * preemptive regeneration and $checkKeys can result in a non-false current value.
825 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
826 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
827 * regeneration will automatically be triggered using the callback.
829 * The $ttl argument and "hotTTR" option (in $opts) use time-dependant randomization
830 * to avoid stampedes. Keys that are slow to regenerate and either heavily used
831 * or subject to explicit (unpredictable) purges, may need additional mechanisms.
832 * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts).
833 * If explicit purges are needed, also:
834 * - a) Pass $key into $checkKeys
835 * - b) Use touchCheckKey( $key ) instead of delete( $key )
837 * Example usage (typical key):
839 * $catInfo = $cache->getWithSetCallback(
840 * // Key to store the cached value under
841 * $cache->makeKey( 'cat-attributes', $catId ),
842 * // Time-to-live (in seconds)
843 * $cache::TTL_MINUTE,
844 * // Function that derives the new key value
845 * function ( $oldValue, &$ttl, array &$setOpts ) {
846 * $dbr = wfGetDB( DB_REPLICA );
847 * // Account for any snapshot/replica DB lag
848 * $setOpts += Database::getCacheSetOptions( $dbr );
850 * return $dbr->selectRow( ... );
855 * Example usage (key that is expensive and hot):
857 * $catConfig = $cache->getWithSetCallback(
858 * // Key to store the cached value under
859 * $cache->makeKey( 'site-cat-config' ),
860 * // Time-to-live (in seconds)
862 * // Function that derives the new key value
863 * function ( $oldValue, &$ttl, array &$setOpts ) {
864 * $dbr = wfGetDB( DB_REPLICA );
865 * // Account for any snapshot/replica DB lag
866 * $setOpts += Database::getCacheSetOptions( $dbr );
868 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
871 * // Calling touchCheckKey() on this key invalidates the cache
872 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
873 * // Try to only let one datacenter thread manage cache updates at a time
875 * // Avoid querying cache servers multiple times in a web request
876 * 'pcTTL' => $cache::TTL_PROC_LONG
881 * Example usage (key with dynamic dependencies):
883 * $catState = $cache->getWithSetCallback(
884 * // Key to store the cached value under
885 * $cache->makeKey( 'cat-state', $cat->getId() ),
886 * // Time-to-live (seconds)
888 * // Function that derives the new key value
889 * function ( $oldValue, &$ttl, array &$setOpts ) {
890 * // Determine new value from the DB
891 * $dbr = wfGetDB( DB_REPLICA );
892 * // Account for any snapshot/replica DB lag
893 * $setOpts += Database::getCacheSetOptions( $dbr );
895 * return CatState::newFromResults( $dbr->select( ... ) );
898 * // The "check" keys that represent things the value depends on;
899 * // Calling touchCheckKey() on any of them invalidates the cache
901 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
902 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
903 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
909 * Example usage (hot key holding most recent 100 events):
911 * $lastCatActions = $cache->getWithSetCallback(
912 * // Key to store the cached value under
913 * $cache->makeKey( 'cat-last-actions', 100 ),
914 * // Time-to-live (in seconds)
916 * // Function that derives the new key value
917 * function ( $oldValue, &$ttl, array &$setOpts ) {
918 * $dbr = wfGetDB( DB_REPLICA );
919 * // Account for any snapshot/replica DB lag
920 * $setOpts += Database::getCacheSetOptions( $dbr );
922 * // Start off with the last cached list
923 * $list = $oldValue ?: [];
924 * // Fetch the last 100 relevant rows in descending order;
925 * // only fetch rows newer than $list[0] to reduce scanning
926 * $rows = iterator_to_array( $dbr->select( ... ) );
927 * // Merge them and get the new "last 100" rows
928 * return array_slice( array_merge( $new, $list ), 0, 100 );
931 * // Try to only let one datacenter thread manage cache updates at a time
933 * // Use a magic value when no cache value is ready rather than stampeding
934 * 'busyValue' => 'computing'
939 * Example usage (key holding an LRU subkey:value map; this can avoid flooding cache with
940 * keys for an unlimited set of (constraint,situation) pairs, thereby avoiding elevated
941 * cache evictions and wasted memory):
943 * $catSituationTolerabilityCache = $this->cache->getWithSetCallback(
944 * // Group by constraint ID/hash, cat family ID/hash, or something else useful
945 * $this->cache->makeKey( 'cat-situation-tolerablity-checks', $groupKey ),
946 * WANObjectCache::TTL_DAY, // rarely used groups should fade away
947 * // The $scenarioKey format is $constraintId:<ID/hash of $situation>
948 * function ( $cacheMap ) use ( $scenarioKey, $constraintId, $situation ) {
949 * $lruCache = MapCacheLRU::newFromArray( $cacheMap ?: [], self::CACHE_SIZE );
950 * $result = $lruCache->get( $scenarioKey ); // triggers LRU bump if present
951 * if ( $result === null || $this->isScenarioResultExpired( $result ) ) {
952 * $result = $this->checkScenarioTolerability( $constraintId, $situation );
953 * $lruCache->set( $scenarioKey, $result, 3 / 8 );
955 * // Save the new LRU cache map and reset the map's TTL
956 * return $lruCache->toArray();
959 * // Once map is > 1 sec old, consider refreshing
961 * // Update within 5 seconds after "ageNew" given a 1hz cache check rate
963 * // Avoid querying cache servers multiple times in a request; this also means
964 * // that a request can only alter the value of any given constraint key once
965 * 'pcTTL' => WANObjectCache::TTL_PROC_LONG
968 * $tolerability = isset( $catSituationTolerabilityCache[$scenarioKey] )
969 * ? $catSituationTolerabilityCache[$scenarioKey]
970 * : $this->checkScenarioTolerability( $constraintId, $situation );
973 * @see WANObjectCache::get()
974 * @see WANObjectCache::set()
976 * @param string $key Cache key made from makeKey() or makeGlobalKey()
977 * @param int $ttl Seconds to live for key updates. Special values are:
978 * - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
979 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
980 * @param callable $callback Value generation function
981 * @param array $opts Options map:
982 * - checkKeys: List of "check" keys. The key at $key will be seen as stale when either
983 * touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This
984 * is useful if thousands or millions of keys depend on the same entity. The entity can
985 * simply have its "check" key updated whenever the entity is modified.
987 * - graceTTL: If the key is invalidated (by "checkKeys") less than this many seconds ago,
988 * consider reusing the stale value. The odds of a refresh becomes more likely over time,
989 * becoming certain once the grace period is reached. This can reduce traffic spikes
990 * when millions of keys are compared to the same "check" key and touchCheckKey() or
991 * resetCheckKey() is called on that "check" key. This option is not useful for the
992 * case of the key simply expiring on account of its TTL (use "lowTTL" instead).
993 * Default: WANObjectCache::GRACE_TTL_NONE.
994 * - lockTSE: If the key is tombstoned or invalidated (by "checkKeys") less than this many
995 * seconds ago, try to have a single thread handle cache regeneration at any given time.
996 * Other threads will try to use stale values if possible. If, on miss, the time since
997 * expiration is low, the assumption is that the key is hot and that a stampede is worth
998 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
999 * higher this is set, the higher the worst-case staleness can be. This option does not
1000 * by itself handle the case of the key simply expiring on account of its TTL, so make
1001 * sure that "lowTTL" is not disabled when using this option.
1002 * Use WANObjectCache::TSE_NONE to disable this logic.
1003 * Default: WANObjectCache::TSE_NONE.
1004 * - busyValue: If no value exists and another thread is currently regenerating it, use this
1005 * as a fallback value (or a callback to generate such a value). This assures that cache
1006 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
1007 * against cache regeneration becoming very slow for some reason (greater than the TTL).
1009 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
1010 * network I/O when a key is read several times. This will not cache when the callback
1011 * returns false, however. Note that any purges will not be seen while process cached;
1012 * since the callback should use replica DBs and they may be lagged or have snapshot
1013 * isolation anyway, this should not typically matter.
1014 * Default: WANObjectCache::TTL_UNCACHEABLE.
1015 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
1016 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
1017 * large values, small yet numerous values, or some values with a high cost of eviction.
1018 * It is generally preferable to use a class constant when setting this value.
1019 * This has no effect unless pcTTL is used.
1020 * Default: WANObjectCache::PC_PRIMARY.
1021 * - version: Integer version number. This allows for callers to make breaking changes to
1022 * how values are stored while maintaining compatability and correct cache purges. New
1023 * versions are stored alongside older versions concurrently. Avoid storing class objects
1024 * however, as this reduces compatibility (due to serialization).
1026 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
1027 * This is useful if the source of a key is suspected of having possibly changed
1028 * recently, and the caller wants any such changes to be reflected.
1029 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
1030 * - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per
1031 * second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this
1032 * TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old.
1033 * This uses randomization to avoid triggering cache stampedes. The TTR is useful at
1034 * reducing the impact of missed cache purges, since the effect of a heavily referenced
1035 * key being stale is worse than that of a rarely referenced key. Unlike simply lowering
1036 * $ttl, seldomly used keys are largely unaffected by this option, which makes it
1037 * possible to have a high hit rate for the "long-tail" of less-used keys.
1038 * Default: WANObjectCache::HOT_TTR.
1039 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
1040 * than this. It becomes more likely over time, becoming certain once the key is expired.
1041 * This helps avoid cache stampedes that might be triggered due to the key expiring.
1042 * Default: WANObjectCache::LOW_TTL.
1043 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
1044 * Default: WANObjectCache::AGE_NEW.
1045 * - staleTTL: Seconds to keep the key around if it is stale. This means that on cache
1046 * miss the callback may get $oldValue/$oldAsOf values for keys that have already been
1047 * expired for this specified time. This is useful if adaptiveTTL() is used on the old
1048 * value's as-of time when it is verified as still being correct.
1049 * Default: WANObjectCache::STALE_TTL_NONE
1050 * @return mixed Value found or written to the key
1051 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
1052 * @note Options added in 1.31: staleTTL, graceTTL
1053 * @note Callable type hints are not used to avoid class-autoloading
1055 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
1056 $pcTTL = $opts['pcTTL'] ?? self
::TTL_UNCACHEABLE
;
1058 // Try the process cache if enabled and the cache callback is not within a cache callback.
1059 // Process cache use in nested callbacks is not lag-safe with regard to HOLDOFF_TTL since
1060 // the in-memory value is further lagged than the shared one since it uses a blind TTL.
1061 if ( $pcTTL >= 0 && $this->callbackDepth
== 0 ) {
1062 $group = $opts['pcGroup'] ?? self
::PC_PRIMARY
;
1063 $procCache = $this->getProcessCache( $group );
1064 $value = $procCache->get( $key );
1070 if ( $value === false ) {
1071 // Fetch the value over the network
1072 if ( isset( $opts['version'] ) ) {
1073 $version = $opts['version'];
1075 $cur = $this->doGetWithSetCallback(
1078 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1079 use ( $callback, $version ) {
1080 if ( is_array( $oldValue )
1081 && array_key_exists( self
::VFLD_DATA
, $oldValue )
1082 && array_key_exists( self
::VFLD_VERSION
, $oldValue )
1083 && $oldValue[self
::VFLD_VERSION
] === $version
1085 $oldData = $oldValue[self
::VFLD_DATA
];
1087 // VFLD_DATA is not set if an old, unversioned, key is present
1093 self
::VFLD_DATA
=> $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
1094 self
::VFLD_VERSION
=> $version
1100 if ( $cur[self
::VFLD_VERSION
] === $version ) {
1101 // Value created or existed before with version; use it
1102 $value = $cur[self
::VFLD_DATA
];
1104 // Value existed before with a different version; use variant key.
1105 // Reflect purges to $key by requiring that this key value be newer.
1106 $value = $this->doGetWithSetCallback(
1107 $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), $version ),
1110 // Regenerate value if not newer than $key
1111 [ 'version' => null, 'minAsOf' => $asOf ] +
$opts
1115 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
1118 // Update the process cache if enabled
1119 if ( $procCache && $value !== false ) {
1120 $procCache->set( $key, $value, $pcTTL );
1128 * Do the actual I/O for getWithSetCallback() when needed
1130 * @see WANObjectCache::getWithSetCallback()
1132 * @param string $key
1134 * @param callback $callback
1135 * @param array $opts Options map for getWithSetCallback()
1136 * @param float &$asOf Cache generation timestamp of returned value [returned]
1138 * @note Callable type hints are not used to avoid class-autoloading
1140 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
1141 $lowTTL = $opts['lowTTL'] ??
min( self
::LOW_TTL
, $ttl );
1142 $lockTSE = $opts['lockTSE'] ?? self
::TSE_NONE
;
1143 $staleTTL = $opts['staleTTL'] ?? self
::STALE_TTL_NONE
;
1144 $graceTTL = $opts['graceTTL'] ?? self
::GRACE_TTL_NONE
;
1145 $checkKeys = $opts['checkKeys'] ??
[];
1146 $busyValue = $opts['busyValue'] ??
null;
1147 $popWindow = $opts['hotTTR'] ?? self
::HOT_TTR
;
1148 $ageNew = $opts['ageNew'] ?? self
::AGE_NEW
;
1149 $minTime = $opts['minAsOf'] ?? self
::MIN_TIMESTAMP_NONE
;
1150 $versioned = isset( $opts['version'] );
1152 // Get a collection name to describe this class of key
1153 $kClass = $this->determineKeyClass( $key );
1155 // Get the current key value
1157 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
1158 $value = $cValue; // return value
1160 $preCallbackTime = $this->getCurrentTime();
1161 // Determine if a cached value regeneration is needed or desired
1162 if ( $value !== false
1163 && $this->isAliveOrInGracePeriod( $curTTL, $graceTTL )
1164 && $this->isValid( $value, $versioned, $asOf, $minTime )
1166 $preemptiveRefresh = (
1167 $this->worthRefreshExpiring( $curTTL, $lowTTL ) ||
1168 $this->worthRefreshPopular( $asOf, $ageNew, $popWindow, $preCallbackTime )
1171 if ( !$preemptiveRefresh ) {
1172 $this->stats
->increment( "wanobjectcache.$kClass.hit.good" );
1175 } elseif ( $this->asyncHandler
) {
1176 // Update the cache value later, such during post-send of an HTTP request
1177 $func = $this->asyncHandler
;
1178 $func( function () use ( $key, $ttl, $callback, $opts, $asOf ) {
1179 $opts['minAsOf'] = INF
; // force a refresh
1180 $this->doGetWithSetCallback( $key, $ttl, $callback, $opts, $asOf );
1182 $this->stats
->increment( "wanobjectcache.$kClass.hit.refresh" );
1188 // A deleted key with a negative TTL left must be tombstoned
1189 $isTombstone = ( $curTTL !== null && $value === false );
1190 if ( $isTombstone && $lockTSE <= 0 ) {
1191 // Use the INTERIM value for tombstoned keys to reduce regeneration load
1192 $lockTSE = self
::INTERIM_KEY_TTL
;
1194 // Assume a key is hot if requested soon after invalidation
1195 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
1196 // Use the mutex if there is no value and a busy fallback is given
1197 $checkBusy = ( $busyValue !== null && $value === false );
1198 // Decide whether a single thread should handle regenerations.
1199 // This avoids stampedes when $checkKeys are bumped and when preemptive
1200 // renegerations take too long. It also reduces regenerations while $key
1201 // is tombstoned. This balances cache freshness with avoiding DB load.
1202 $useMutex = ( $isHot ||
( $isTombstone && $lockTSE > 0 ) ||
$checkBusy );
1204 $lockAcquired = false;
1206 // Acquire a datacenter-local non-blocking lock
1207 if ( $this->cache
->add( self
::MUTEX_KEY_PREFIX
. $key, 1, self
::LOCK_TTL
) ) {
1208 // Lock acquired; this thread should update the key
1209 $lockAcquired = true;
1210 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1211 $this->stats
->increment( "wanobjectcache.$kClass.hit.stale" );
1212 // If it cannot be acquired; then the stale value can be used
1215 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
1216 // For hot keys, either another thread has the lock or the lock failed;
1217 // use the INTERIM value from the last thread that regenerated it.
1218 $value = $this->getInterimValue( $key, $versioned, $minTime, $asOf );
1219 if ( $value !== false ) {
1220 $this->stats
->increment( "wanobjectcache.$kClass.hit.volatile" );
1224 // Use the busy fallback value if nothing else
1225 if ( $busyValue !== null ) {
1226 $this->stats
->increment( "wanobjectcache.$kClass.miss.busy" );
1228 return is_callable( $busyValue ) ?
$busyValue() : $busyValue;
1233 if ( !is_callable( $callback ) ) {
1234 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
1237 // Generate the new value from the callback...
1239 ++
$this->callbackDepth
;
1241 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
1243 --$this->callbackDepth
;
1245 $valueIsCacheable = ( $value !== false && $ttl >= 0 );
1247 // When delete() is called, writes are write-holed by the tombstone,
1248 // so use a special INTERIM key to pass the new value around threads.
1249 if ( ( $isTombstone && $lockTSE > 0 ) && $valueIsCacheable ) {
1250 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
1251 $newAsOf = $this->getCurrentTime();
1252 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
1253 // Avoid using set() to avoid pointless mcrouter broadcasting
1254 $this->setInterimValue( $key, $wrapped, $tempTTL );
1257 if ( $valueIsCacheable ) {
1258 $setOpts['lockTSE'] = $lockTSE;
1259 $setOpts['staleTTL'] = $staleTTL;
1260 // Use best known "since" timestamp if not provided
1261 $setOpts +
= [ 'since' => $preCallbackTime ];
1262 // Update the cache; this will fail if the key is tombstoned
1263 $this->set( $key, $value, $ttl, $setOpts );
1266 if ( $lockAcquired ) {
1267 // Avoid using delete() to avoid pointless mcrouter broadcasting
1268 $this->cache
->changeTTL( self
::MUTEX_KEY_PREFIX
. $key, (int)$preCallbackTime - 60 );
1271 $this->stats
->increment( "wanobjectcache.$kClass.miss.compute" );
1277 * @param string $key
1278 * @param bool $versioned
1279 * @param float $minTime
1280 * @param mixed &$asOf
1283 protected function getInterimValue( $key, $versioned, $minTime, &$asOf ) {
1284 if ( !$this->useInterimHoldOffCaching
) {
1285 return false; // disabled
1288 $wrapped = $this->cache
->get( self
::INTERIM_KEY_PREFIX
. $key );
1289 list( $value ) = $this->unwrap( $wrapped, $this->getCurrentTime() );
1290 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1291 $asOf = $wrapped[self
::FLD_TIME
];
1300 * @param string $key
1301 * @param array $wrapped
1302 * @param int $tempTTL
1304 protected function setInterimValue( $key, $wrapped, $tempTTL ) {
1305 $this->cache
->merge(
1306 self
::INTERIM_KEY_PREFIX
. $key,
1307 function () use ( $wrapped ) {
1316 * Method to fetch multiple cache keys at once with regeneration
1318 * This works the same as getWithSetCallback() except:
1319 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1320 * - b) The $callback argument expects a callback taking the following arguments:
1321 * - $id: ID of an entity to query
1322 * - $oldValue : the prior cache value or false if none was present
1323 * - &$ttl : a reference to the new value TTL in seconds
1324 * - &$setOpts : a reference to options for set() which can be altered
1325 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present
1326 * Aside from the additional $id argument, the other arguments function the same
1327 * way they do in getWithSetCallback().
1328 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1330 * @see WANObjectCache::getWithSetCallback()
1331 * @see WANObjectCache::getMultiWithUnionSetCallback()
1335 * $rows = $cache->getMultiWithSetCallback(
1336 * // Map of cache keys to entity IDs
1337 * $cache->makeMultiKeys(
1338 * $this->fileVersionIds(),
1339 * function ( $id, WANObjectCache $cache ) {
1340 * return $cache->makeKey( 'file-version', $id );
1343 * // Time-to-live (in seconds)
1345 * // Function that derives the new key value
1346 * function ( $id, $oldValue, &$ttl, array &$setOpts ) {
1347 * $dbr = wfGetDB( DB_REPLICA );
1348 * // Account for any snapshot/replica DB lag
1349 * $setOpts += Database::getCacheSetOptions( $dbr );
1351 * // Load the row for this file
1352 * $queryInfo = File::getQueryInfo();
1353 * $row = $dbr->selectRow(
1354 * $queryInfo['tables'],
1355 * $queryInfo['fields'],
1359 * $queryInfo['joins']
1362 * return $row ? (array)$row : false;
1365 * // Process cache for 30 seconds
1367 * // Use a dedicated 500 item cache (initialized on-the-fly)
1368 * 'pcGroup' => 'file-versions:500'
1371 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1374 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1375 * @param int $ttl Seconds to live for key updates
1376 * @param callable $callback Callback the yields entity regeneration callbacks
1377 * @param array $opts Options map
1378 * @return array Map of (cache key => value) in the same order as $keyedIds
1381 final public function getMultiWithSetCallback(
1382 ArrayIterator
$keyedIds, $ttl, callable
$callback, array $opts = []
1384 $valueKeys = array_keys( $keyedIds->getArrayCopy() );
1385 $checkKeys = $opts['checkKeys'] ??
[];
1387 // Load required keys into process cache in one go
1388 $this->warmupCache
= $this->getRawKeysForWarmup(
1389 $this->getNonProcessCachedKeys( $valueKeys, $opts ),
1392 $this->warmupKeyMisses
= 0;
1394 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1395 $id = null; // current entity ID
1396 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf ) use ( $callback, &$id ) {
1397 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1401 foreach ( $keyedIds as $key => $id ) { // preserve order
1402 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1405 $this->warmupCache
= [];
1411 * Method to fetch/regenerate multiple cache keys at once
1413 * This works the same as getWithSetCallback() except:
1414 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1415 * - b) The $callback argument expects a callback returning a map of (ID => new value)
1416 * for all entity IDs in $ids and it takes the following arguments:
1417 * - $ids: a list of entity IDs that require cache regeneration
1418 * - &$ttls: a reference to the (entity ID => new TTL) map
1419 * - &$setOpts: a reference to options for set() which can be altered
1420 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1421 * - d) The "lockTSE" and "busyValue" options are ignored
1423 * @see WANObjectCache::getWithSetCallback()
1424 * @see WANObjectCache::getMultiWithSetCallback()
1428 * $rows = $cache->getMultiWithUnionSetCallback(
1429 * // Map of cache keys to entity IDs
1430 * $cache->makeMultiKeys(
1431 * $this->fileVersionIds(),
1432 * function ( $id, WANObjectCache $cache ) {
1433 * return $cache->makeKey( 'file-version', $id );
1436 * // Time-to-live (in seconds)
1438 * // Function that derives the new key value
1439 * function ( array $ids, array &$ttls, array &$setOpts ) {
1440 * $dbr = wfGetDB( DB_REPLICA );
1441 * // Account for any snapshot/replica DB lag
1442 * $setOpts += Database::getCacheSetOptions( $dbr );
1444 * // Load the rows for these files
1446 * $queryInfo = File::getQueryInfo();
1447 * $res = $dbr->select(
1448 * $queryInfo['tables'],
1449 * $queryInfo['fields'],
1453 * $queryInfo['joins']
1455 * foreach ( $res as $row ) {
1456 * $rows[$row->id] = $row;
1457 * $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
1458 * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
1465 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1468 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1469 * @param int $ttl Seconds to live for key updates
1470 * @param callable $callback Callback the yields entity regeneration callbacks
1471 * @param array $opts Options map
1472 * @return array Map of (cache key => value) in the same order as $keyedIds
1475 final public function getMultiWithUnionSetCallback(
1476 ArrayIterator
$keyedIds, $ttl, callable
$callback, array $opts = []
1478 $idsByValueKey = $keyedIds->getArrayCopy();
1479 $valueKeys = array_keys( $idsByValueKey );
1480 $checkKeys = $opts['checkKeys'] ??
[];
1481 unset( $opts['lockTSE'] ); // incompatible
1482 unset( $opts['busyValue'] ); // incompatible
1484 // Load required keys into process cache in one go
1485 $keysGet = $this->getNonProcessCachedKeys( $valueKeys, $opts );
1486 $this->warmupCache
= $this->getRawKeysForWarmup( $keysGet, $checkKeys );
1487 $this->warmupKeyMisses
= 0;
1489 // IDs of entities known to be in need of regeneration
1492 // Find out which keys are missing/deleted/stale
1495 $curByKey = $this->getMulti( $keysGet, $curTTLs, $checkKeys, $asOfs );
1496 foreach ( $keysGet as $key ) {
1497 if ( !array_key_exists( $key, $curByKey ) ||
$curTTLs[$key] < 0 ) {
1498 $idsRegen[] = $idsByValueKey[$key];
1502 // Run the callback to populate the regeneration value map for all required IDs
1504 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
1505 $newValsById = $idsRegen ?
$callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
1507 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1508 $id = null; // current entity ID
1509 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1510 use ( $callback, &$id, $newValsById, $newTTLsById, $newSetOpts )
1512 if ( array_key_exists( $id, $newValsById ) ) {
1513 // Value was already regerated as expected, so use the value in $newValsById
1514 $newValue = $newValsById[$id];
1515 $ttl = $newTTLsById[$id];
1516 $setOpts = $newSetOpts;
1518 // Pre-emptive/popularity refresh and version mismatch cases are not detected
1519 // above and thus $newValsById has no entry. Run $callback on this single entity.
1520 $ttls = [ $id => $ttl ];
1521 $newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
1528 // Run the cache-aside logic using warmupCache instead of persistent cache queries
1530 foreach ( $idsByValueKey as $key => $id ) { // preserve order
1531 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1534 $this->warmupCache
= [];
1540 * Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1542 * This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids
1543 * broadcasting in mcrouter setups and also avoids races with new tombstones.
1545 * @param string $key Cache key
1546 * @param int $purgeTimestamp UNIX timestamp of purge
1547 * @param bool &$isStale Whether the key is stale
1548 * @return bool Success
1551 final public function reap( $key, $purgeTimestamp, &$isStale = false ) {
1552 $minAsOf = $purgeTimestamp + self
::HOLDOFF_TTL
;
1553 $wrapped = $this->cache
->get( self
::VALUE_KEY_PREFIX
. $key );
1554 if ( is_array( $wrapped ) && $wrapped[self
::FLD_TIME
] < $minAsOf ) {
1556 $this->logger
->warning( "Reaping stale value key '$key'." );
1557 $ttlReap = self
::HOLDOFF_TTL
; // avoids races with tombstone creation
1558 $ok = $this->cache
->changeTTL( self
::VALUE_KEY_PREFIX
. $key, $ttlReap );
1560 $this->logger
->error( "Could not complete reap of key '$key'." );
1572 * Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1574 * @param string $key Cache key
1575 * @param int $purgeTimestamp UNIX timestamp of purge
1576 * @param bool &$isStale Whether the key is stale
1577 * @return bool Success
1580 final public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
1581 $purge = $this->parsePurgeValue( $this->cache
->get( self
::TIME_KEY_PREFIX
. $key ) );
1582 if ( $purge && $purge[self
::FLD_TIME
] < $purgeTimestamp ) {
1584 $this->logger
->warning( "Reaping stale check key '$key'." );
1585 $ok = $this->cache
->changeTTL( self
::TIME_KEY_PREFIX
. $key, self
::TTL_SECOND
);
1587 $this->logger
->error( "Could not complete reap of check key '$key'." );
1599 * @see BagOStuff::makeKey()
1600 * @param string $class Key class
1601 * @param string $component [optional] Key component (starting with a key collection name)
1602 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1605 public function makeKey( $class, $component = null ) {
1606 return call_user_func_array( [ $this->cache
, __FUNCTION__
], func_get_args() );
1610 * @see BagOStuff::makeGlobalKey()
1611 * @param string $class Key class
1612 * @param string $component [optional] Key component (starting with a key collection name)
1613 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1616 public function makeGlobalKey( $class, $component = null ) {
1617 return call_user_func_array( [ $this->cache
, __FUNCTION__
], func_get_args() );
1621 * @param array $entities List of entity IDs
1622 * @param callable $keyFunc Callback yielding a key from (entity ID, this WANObjectCache)
1623 * @return ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
1626 final public function makeMultiKeys( array $entities, callable
$keyFunc ) {
1628 foreach ( $entities as $entity ) {
1629 $map[$keyFunc( $entity, $this )] = $entity;
1632 return new ArrayIterator( $map );
1636 * Get the "last error" registered; clearLastError() should be called manually
1637 * @return int ERR_* class constant for the "last error" registry
1639 final public function getLastError() {
1640 if ( $this->lastRelayError
) {
1641 // If the cache and the relayer failed, focus on the latter.
1642 // An update not making it to the relayer means it won't show up
1643 // in other DCs (nor will consistent re-hashing see up-to-date values).
1644 // On the other hand, if just the cache update failed, then it should
1645 // eventually be applied by the relayer.
1646 return $this->lastRelayError
;
1649 $code = $this->cache
->getLastError();
1651 case BagOStuff
::ERR_NONE
:
1652 return self
::ERR_NONE
;
1653 case BagOStuff
::ERR_NO_RESPONSE
:
1654 return self
::ERR_NO_RESPONSE
;
1655 case BagOStuff
::ERR_UNREACHABLE
:
1656 return self
::ERR_UNREACHABLE
;
1658 return self
::ERR_UNEXPECTED
;
1663 * Clear the "last error" registry
1665 final public function clearLastError() {
1666 $this->cache
->clearLastError();
1667 $this->lastRelayError
= self
::ERR_NONE
;
1671 * Clear the in-process caches; useful for testing
1675 public function clearProcessCache() {
1676 $this->processCaches
= [];
1680 * Enable or disable the use of brief caching for tombstoned keys
1682 * When a key is purged via delete(), there normally is a period where caching
1683 * is hold-off limited to an extremely short time. This method will disable that
1684 * caching, forcing the callback to run for any of:
1685 * - WANObjectCache::getWithSetCallback()
1686 * - WANObjectCache::getMultiWithSetCallback()
1687 * - WANObjectCache::getMultiWithUnionSetCallback()
1689 * This is useful when both:
1690 * - a) the database used by the callback is known to be up-to-date enough
1691 * for some particular purpose (e.g. replica DB has applied transaction X)
1692 * - b) the caller needs to exploit that fact, and therefore needs to avoid the
1693 * use of inherently volatile and possibly stale interim keys
1695 * @see WANObjectCache::delete()
1696 * @param bool $enabled Whether to enable interim caching
1699 final public function useInterimHoldOffCaching( $enabled ) {
1700 $this->useInterimHoldOffCaching
= $enabled;
1704 * @param int $flag ATTR_* class constant
1705 * @return int QOS_* class constant
1708 public function getQoS( $flag ) {
1709 return $this->cache
->getQoS( $flag );
1713 * Get a TTL that is higher for objects that have not changed recently
1715 * This is useful for keys that get explicit purges and DB or purge relay
1716 * lag is a potential concern (especially how it interacts with CDN cache)
1720 * // Last-modified time of page
1721 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1722 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1723 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1724 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1725 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1728 * Another use case is when there are no applicable "last modified" fields in the DB,
1729 * and there are too many dependencies for explicit purges to be viable, and the rate of
1730 * change to relevant content is unstable, and it is highly valued to have the cached value
1731 * be as up-to-date as possible.
1735 * $query = "<some complex query>";
1736 * $idListFromComplexQuery = $cache->getWithSetCallback(
1737 * $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
1738 * GraphQueryClass::STARTING_TTL,
1739 * function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
1740 * $gdb = $this->getReplicaGraphDbConnection();
1741 * // Account for any snapshot/replica DB lag
1742 * $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
1744 * $newList = iterator_to_array( $gdb->query( $query ) );
1745 * sort( $newList, SORT_NUMERIC ); // normalize
1747 * $minTTL = GraphQueryClass::MIN_TTL;
1748 * $maxTTL = GraphQueryClass::MAX_TTL;
1749 * if ( $oldValue !== false ) {
1750 * // Note that $oldAsOf is the last time this callback ran
1751 * $ttl = ( $newList === $oldValue )
1752 * // No change: cache for 150% of the age of $oldValue
1753 * ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
1754 * // Changed: cache for 50% of the age of $oldValue
1755 * : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
1761 * // Keep stale values around for doing comparisons for TTL calculations.
1762 * // High values improve long-tail keys hit-rates, though might waste space.
1763 * 'staleTTL' => GraphQueryClass::GRACE_TTL
1768 * @param int|float $mtime UNIX timestamp
1769 * @param int $maxTTL Maximum TTL (seconds)
1770 * @param int $minTTL Minimum TTL (seconds); Default: 30
1771 * @param float $factor Value in the range (0,1); Default: .2
1772 * @return int Adaptive TTL
1775 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
1776 if ( is_float( $mtime ) ||
ctype_digit( $mtime ) ) {
1777 $mtime = (int)$mtime; // handle fractional seconds and string integers
1780 if ( !is_int( $mtime ) ||
$mtime <= 0 ) {
1781 return $minTTL; // no last-modified time provided
1784 $age = $this->getCurrentTime() - $mtime;
1786 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1790 * @return int Number of warmup key cache misses last round
1793 final public function getWarmupKeyMisses() {
1794 return $this->warmupKeyMisses
;
1798 * Do the actual async bus purge of a key
1800 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1802 * @param string $key Cache key
1803 * @param int $ttl How long to keep the tombstone [seconds]
1804 * @param int $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1805 * @return bool Success
1807 protected function relayPurge( $key, $ttl, $holdoff ) {
1808 if ( $this->mcrouterAware
) {
1809 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
1810 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
1811 $ok = $this->cache
->set(
1812 "/*/{$this->cluster}/{$key}",
1813 $this->makePurgeValue( $this->getCurrentTime(), self
::HOLDOFF_NONE
),
1816 } elseif ( $this->purgeRelayer
instanceof EventRelayerNull
) {
1817 // This handles the mcrouter and the single-DC case
1818 $ok = $this->cache
->set(
1820 $this->makePurgeValue( $this->getCurrentTime(), self
::HOLDOFF_NONE
),
1824 $event = $this->cache
->modifySimpleRelayEvent( [
1827 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1828 'ttl' => max( $ttl, self
::TTL_SECOND
),
1829 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1832 $ok = $this->purgeRelayer
->notify( $this->purgeChannel
, $event );
1834 $this->lastRelayError
= self
::ERR_RELAY
;
1842 * Do the actual async bus delete of a key
1844 * @param string $key Cache key
1845 * @return bool Success
1847 protected function relayDelete( $key ) {
1848 if ( $this->mcrouterAware
) {
1849 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
1850 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
1851 $ok = $this->cache
->delete( "/*/{$this->cluster}/{$key}" );
1852 } elseif ( $this->purgeRelayer
instanceof EventRelayerNull
) {
1853 // Some other proxy handles broadcasting or there is only one datacenter
1854 $ok = $this->cache
->delete( $key );
1856 $event = $this->cache
->modifySimpleRelayEvent( [
1861 $ok = $this->purgeRelayer
->notify( $this->purgeChannel
, $event );
1863 $this->lastRelayError
= self
::ERR_RELAY
;
1871 * Check if a key is fresh or in the grace window and thus due for randomized reuse
1873 * If $curTTL > 0 (e.g. not expired) this returns true. Otherwise, the chance of returning
1874 * true decrease steadily from 100% to 0% as the |$curTTL| moves from 0 to $graceTTL seconds.
1875 * This handles widely varying levels of cache access traffic.
1877 * If $curTTL <= -$graceTTL (e.g. already expired), then this returns false.
1879 * @param float $curTTL Approximate TTL left on the key if present
1880 * @param int $graceTTL Consider using stale values if $curTTL is greater than this
1883 protected function isAliveOrInGracePeriod( $curTTL, $graceTTL ) {
1884 if ( $curTTL > 0 ) {
1886 } elseif ( $graceTTL <= 0 ) {
1890 $ageStale = abs( $curTTL ); // seconds of staleness
1891 $curGTTL = ( $graceTTL - $ageStale ); // current grace-time-to-live
1892 if ( $curGTTL <= 0 ) {
1893 return false; // already out of grace period
1896 // Chance of using a stale value is the complement of the chance of refreshing it
1897 return !$this->worthRefreshExpiring( $curGTTL, $graceTTL );
1901 * Check if a key is nearing expiration and thus due for randomized regeneration
1903 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance of returning true
1904 * increases steadily from 0% to 100% as the $curTTL moves from $lowTTL to 0 seconds.
1905 * This handles widely varying levels of cache access traffic.
1907 * If $curTTL <= 0 (e.g. already expired), then this returns false.
1909 * @param float $curTTL Approximate TTL left on the key if present
1910 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1913 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1914 if ( $lowTTL <= 0 ) {
1916 } elseif ( $curTTL >= $lowTTL ) {
1918 } elseif ( $curTTL <= 0 ) {
1922 $chance = ( 1 - $curTTL / $lowTTL );
1924 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
1928 * Check if a key is due for randomized regeneration due to its popularity
1930 * This is used so that popular keys can preemptively refresh themselves for higher
1931 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
1932 * in cache with their high nominal TTL. This means popular keys keep good consistency,
1933 * whether the data changes frequently or not, and long-tail keys get to stay in cache
1934 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
1936 * @param float $asOf UNIX timestamp of the value
1937 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
1938 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
1939 * @param float $now The current UNIX timestamp
1942 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
1943 if ( $ageNew < 0 ||
$timeTillRefresh <= 0 ) {
1947 $age = $now - $asOf;
1948 $timeOld = $age - $ageNew;
1949 if ( $timeOld <= 0 ) {
1953 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
1954 // Note that the "expected # of refreshes" for the ramp-up time range is half of what it
1955 // would be if P(refresh) was at its full value during that time range.
1956 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self
::RAMPUP_TTL
/ 2, 1 );
1957 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1958 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1959 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1960 $chance = 1 / ( self
::HIT_RATE_HIGH
* $refreshWindowSec );
1962 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1963 $chance *= ( $timeOld <= self
::RAMPUP_TTL
) ?
$timeOld / self
::RAMPUP_TTL
: 1;
1965 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
1969 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1971 * @param array $value
1972 * @param bool $versioned
1973 * @param float $asOf The time $value was generated
1974 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1977 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1978 if ( $versioned && !isset( $value[self
::VFLD_VERSION
] ) ) {
1980 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1988 * Do not use this method outside WANObjectCache
1990 * @param mixed $value
1991 * @param int $ttl [0=forever]
1992 * @param float $now Unix Current timestamp just before calling set()
1995 protected function wrap( $value, $ttl, $now ) {
1997 self
::FLD_VERSION
=> self
::VERSION
,
1998 self
::FLD_VALUE
=> $value,
1999 self
::FLD_TTL
=> $ttl,
2000 self
::FLD_TIME
=> $now
2005 * Do not use this method outside WANObjectCache
2007 * @param array|string|bool $wrapped
2008 * @param float $now Unix Current timestamp (preferrably pre-query)
2009 * @return array (mixed; false if absent/tombstoned/malformed, current time left)
2011 protected function unwrap( $wrapped, $now ) {
2012 // Check if the value is a tombstone
2013 $purge = $this->parsePurgeValue( $wrapped );
2014 if ( $purge !== false ) {
2015 // Purged values should always have a negative current $ttl
2016 $curTTL = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
2017 return [ false, $curTTL ];
2020 if ( !is_array( $wrapped ) // not found
2021 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
2022 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
2024 return [ false, null ];
2027 $flags = $wrapped[self
::FLD_FLAGS
] ??
0;
2028 if ( ( $flags & self
::FLG_STALE
) == self
::FLG_STALE
) {
2029 // Treat as expired, with the cache time as the expiration
2030 $age = $now - $wrapped[self
::FLD_TIME
];
2031 $curTTL = min( -$age, self
::TINY_NEGATIVE
);
2032 } elseif ( $wrapped[self
::FLD_TTL
] > 0 ) {
2033 // Get the approximate time left on the key
2034 $age = $now - $wrapped[self
::FLD_TIME
];
2035 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
2037 // Key had no TTL, so the time left is unbounded
2041 return [ $wrapped[self
::FLD_VALUE
], $curTTL ];
2045 * @param array $keys
2046 * @param string $prefix
2049 protected static function prefixCacheKeys( array $keys, $prefix ) {
2051 foreach ( $keys as $key ) {
2052 $res[] = $prefix . $key;
2059 * @param string $key String of the format <scope>:<class>[:<class or variable>]...
2062 protected function determineKeyClass( $key ) {
2063 $parts = explode( ':', $key );
2065 return $parts[1] ??
$parts[0]; // sanity
2069 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
2070 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
2071 * or false if value isn't a valid purge value
2073 protected function parsePurgeValue( $value ) {
2074 if ( !is_string( $value ) ) {
2077 $segments = explode( ':', $value, 3 );
2078 if ( !isset( $segments[0] ) ||
!isset( $segments[1] )
2079 ||
"{$segments[0]}:" !== self
::PURGE_VAL_PREFIX
2083 if ( !isset( $segments[2] ) ) {
2084 // Back-compat with old purge values without holdoff
2085 $segments[2] = self
::HOLDOFF_TTL
;
2088 self
::FLD_TIME
=> (float)$segments[1],
2089 self
::FLD_HOLDOFF
=> (int)$segments[2],
2094 * @param float $timestamp
2095 * @param int $holdoff In seconds
2096 * @return string Wrapped purge value
2098 protected function makePurgeValue( $timestamp, $holdoff ) {
2099 return self
::PURGE_VAL_PREFIX
. (float)$timestamp . ':' . (int)$holdoff;
2103 * @param string $group
2104 * @return HashBagOStuff
2106 protected function getProcessCache( $group ) {
2107 if ( !isset( $this->processCaches
[$group] ) ) {
2108 list( , $n ) = explode( ':', $group );
2109 $this->processCaches
[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
2112 return $this->processCaches
[$group];
2116 * @param array $keys
2117 * @param array $opts
2118 * @return array List of keys
2120 private function getNonProcessCachedKeys( array $keys, array $opts ) {
2122 if ( isset( $opts['pcTTL'] ) && $opts['pcTTL'] > 0 && $this->callbackDepth
== 0 ) {
2123 $pcGroup = $opts['pcGroup'] ?? self
::PC_PRIMARY
;
2124 $procCache = $this->getProcessCache( $pcGroup );
2125 foreach ( $keys as $key ) {
2126 if ( $procCache->get( $key ) !== false ) {
2127 $keysFound[] = $key;
2132 return array_diff( $keys, $keysFound );
2136 * @param array $keys
2137 * @param array $checkKeys
2138 * @return array Map of (cache key => mixed)
2140 private function getRawKeysForWarmup( array $keys, array $checkKeys ) {
2146 // Get all the value keys to fetch...
2147 foreach ( $keys as $key ) {
2148 $keysWarmUp[] = self
::VALUE_KEY_PREFIX
. $key;
2150 // Get all the check keys to fetch...
2151 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
2152 if ( is_int( $i ) ) {
2153 // Single check key that applies to all value keys
2154 $keysWarmUp[] = self
::TIME_KEY_PREFIX
. $checkKeyOrKeys;
2156 // List of check keys that apply to value key $i
2157 $keysWarmUp = array_merge(
2159 self
::prefixCacheKeys( $checkKeyOrKeys, self
::TIME_KEY_PREFIX
)
2164 $warmupCache = $this->cache
->getMulti( $keysWarmUp );
2165 $warmupCache +
= array_fill_keys( $keysWarmUp, false );
2167 return $warmupCache;
2171 * @return float UNIX timestamp
2172 * @codeCoverageIgnore
2174 protected function getCurrentTime() {
2175 return $this->wallClockOverride ?
: microtime( true );
2179 * @param float|null &$time Mock UNIX timestamp for testing
2180 * @codeCoverageIgnore
2182 public function setMockTime( &$time ) {
2183 $this->wallClockOverride
=& $time;
2184 $this->cache
->setMockTime( $time );