Merge "Special:Upload should not crash on failing previews"
[mediawiki.git] / includes / libs / objectcache / WANObjectCache.php
blob171c291cf146693c62e3e75d960b09c6584aa57f
1 <?php
2 /**
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
18 * @file
19 * @ingroup Cache
20 * @author Aaron Schulz
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
27 /**
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 two 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) Ignore the 'purge' EventRelayer configuration (default is NullEventRelayer)
51 * and set up mcrouter as the underlying cache backend, using one of the memcached
52 * BagOStuff classes as 'cache'. Use OperationSelectorRoute in the mcrouter settings
53 * to configure 'set' and 'delete' operations to go to all DCs via AllAsyncRoute and
54 * configure other operations to go to the local DC via PoolRoute (for reference,
55 * see https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles).
57 * Broadcasted operations like delete() and touchCheckKey() are done asynchronously
58 * in all datacenters this way, though the local one should likely be near immediate.
60 * This means that callers in all datacenters may see older values for however many
61 * milliseconds that the purge took to reach that datacenter. As with any cache, this
62 * should not be relied on for cases where reads are used to determine writes to source
63 * (e.g. non-cache) data stores, except when reading immutable data.
65 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
66 * to avoid collisions with keys that are not wrapped as metadata arrays. The
67 * prefixes are as follows:
68 * - a) "WANCache:v" : used for regular value keys
69 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
70 * - c) "WANCache:t" : used for storing timestamp "check" keys
71 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
73 * @ingroup Cache
74 * @since 1.26
76 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
77 /** @var BagOStuff The local datacenter cache */
78 protected $cache;
79 /** @var HashBagOStuff[] Map of group PHP instance caches */
80 protected $processCaches = [];
81 /** @var string Purge channel name */
82 protected $purgeChannel;
83 /** @var EventRelayer Bus that handles purge broadcasts */
84 protected $purgeRelayer;
85 /** @var LoggerInterface */
86 protected $logger;
88 /** @var int ERR_* constant for the "last error" registry */
89 protected $lastRelayError = self::ERR_NONE;
91 /** @var integer Callback stack depth for getWithSetCallback() */
92 private $callbackDepth = 0;
93 /** @var mixed[] Temporary warm-up cache */
94 private $warmupCache = [];
96 /** Max time expected to pass between delete() and DB commit finishing */
97 const MAX_COMMIT_DELAY = 3;
98 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
99 const MAX_READ_LAG = 7;
100 /** Seconds to tombstone keys on delete() */
101 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
103 /** Seconds to keep dependency purge keys around */
104 const CHECK_KEY_TTL = self::TTL_YEAR;
105 /** Seconds to keep lock keys around */
106 const LOCK_TTL = 10;
107 /** Default remaining TTL at which to consider pre-emptive regeneration */
108 const LOW_TTL = 30;
109 /** Default time-since-expiry on a miss that makes a key "hot" */
110 const LOCK_TSE = 1;
112 /** Never consider performing "popularity" refreshes until a key reaches this age */
113 const AGE_NEW = 60;
114 /** The time length of the "popularity" refresh window for hot keys */
115 const HOT_TTR = 900;
116 /** Hits/second for a refresh to be expected within the "popularity" window */
117 const HIT_RATE_HIGH = 1;
118 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
119 const RAMPUP_TTL = 30;
121 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
122 const TTL_UNCACHEABLE = -1;
123 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
124 const TSE_NONE = -1;
125 /** Max TTL to store keys when a data sourced is lagged */
126 const TTL_LAGGED = 30;
127 /** Idiom for delete() for "no hold-off" */
128 const HOLDOFF_NONE = 0;
129 /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
130 const MIN_TIMESTAMP_NONE = 0.0;
132 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
133 const TINY_NEGATIVE = -0.000001;
135 /** Cache format version number */
136 const VERSION = 1;
138 const FLD_VERSION = 0; // key to cache version number
139 const FLD_VALUE = 1; // key to the cached value
140 const FLD_TTL = 2; // key to the original TTL
141 const FLD_TIME = 3; // key to the cache time
142 const FLD_FLAGS = 4; // key to the flags bitfield
143 const FLD_HOLDOFF = 5; // key to any hold-off TTL
145 /** @var integer Treat this value as expired-on-arrival */
146 const FLG_STALE = 1;
148 const ERR_NONE = 0; // no error
149 const ERR_NO_RESPONSE = 1; // no response
150 const ERR_UNREACHABLE = 2; // can't connect
151 const ERR_UNEXPECTED = 3; // response gave some error
152 const ERR_RELAY = 4; // relay broadcast failed
154 const VALUE_KEY_PREFIX = 'WANCache:v:';
155 const INTERIM_KEY_PREFIX = 'WANCache:i:';
156 const TIME_KEY_PREFIX = 'WANCache:t:';
157 const MUTEX_KEY_PREFIX = 'WANCache:m:';
159 const PURGE_VAL_PREFIX = 'PURGED:';
161 const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
162 const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
164 const PC_PRIMARY = 'primary:1000'; // process cache name and max key count
166 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
169 * @param array $params
170 * - cache : BagOStuff object for a persistent cache
171 * - channels : Map of (action => channel string). Actions include "purge".
172 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
173 * - logger : LoggerInterface object
175 public function __construct( array $params ) {
176 $this->cache = $params['cache'];
177 $this->purgeChannel = isset( $params['channels']['purge'] )
178 ? $params['channels']['purge']
179 : self::DEFAULT_PURGE_CHANNEL;
180 $this->purgeRelayer = isset( $params['relayers']['purge'] )
181 ? $params['relayers']['purge']
182 : new EventRelayerNull( [] );
183 $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
186 public function setLogger( LoggerInterface $logger ) {
187 $this->logger = $logger;
191 * Get an instance that wraps EmptyBagOStuff
193 * @return WANObjectCache
195 public static function newEmpty() {
196 return new self( [
197 'cache' => new EmptyBagOStuff(),
198 'pool' => 'empty',
199 'relayer' => new EventRelayerNull( [] )
200 ] );
204 * Fetch the value of a key from cache
206 * If supplied, $curTTL is set to the remaining TTL (current time left):
207 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
208 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
209 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
210 * - d) null; if $key does not exist and is not tombstoned
212 * If a key is tombstoned, $curTTL will reflect the time since delete().
214 * The timestamp of $key will be checked against the last-purge timestamp
215 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
216 * initialized to the current timestamp. If any of $checkKeys have a timestamp
217 * greater than that of $key, then $curTTL will reflect how long ago $key
218 * became invalid. Callers can use $curTTL to know when the value is stale.
219 * The $checkKeys parameter allow mass invalidations by updating a single key:
220 * - a) Each "check" key represents "last purged" of some source data
221 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
222 * - c) When the source data that "check" keys represent changes,
223 * the touchCheckKey() method is called on them
225 * Source data entities might exists in a DB that uses snapshot isolation
226 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
227 * isolation can largely be maintained by doing the following:
228 * - a) Calling delete() on entity change *and* creation, before DB commit
229 * - b) Keeping transaction duration shorter than delete() hold-off TTL
231 * However, pre-snapshot values might still be seen if an update was made
232 * in a remote datacenter but the purge from delete() didn't relay yet.
234 * Consider using getWithSetCallback() instead of get() and set() cycles.
235 * That method has cache slam avoiding features for hot/expensive keys.
237 * @param string $key Cache key
238 * @param mixed $curTTL Approximate TTL left on the key if present/tombstoned [returned]
239 * @param array $checkKeys List of "check" keys
240 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
241 * @return mixed Value of cache key or false on failure
243 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
244 $curTTLs = [];
245 $asOfs = [];
246 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
247 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
248 $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null;
250 return isset( $values[$key] ) ? $values[$key] : false;
254 * Fetch the value of several keys from cache
256 * @see WANObjectCache::get()
258 * @param array $keys List of cache keys
259 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
260 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
261 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
262 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
263 * @return array Map of (key => value) for keys that exist
265 final public function getMulti(
266 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
268 $result = [];
269 $curTTLs = [];
270 $asOfs = [];
272 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
273 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
275 $checkKeysForAll = [];
276 $checkKeysByKey = [];
277 $checkKeysFlat = [];
278 foreach ( $checkKeys as $i => $checkKeyGroup ) {
279 $prefixed = self::prefixCacheKeys( (array)$checkKeyGroup, self::TIME_KEY_PREFIX );
280 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
281 // Is this check keys for a specific cache key, or for all keys being fetched?
282 if ( is_int( $i ) ) {
283 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
284 } else {
285 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
286 ? array_merge( $checkKeysByKey[$i], $prefixed )
287 : $prefixed;
291 // Fetch all of the raw values
292 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
293 if ( $this->warmupCache ) {
294 $wrappedValues = array_intersect_key( $this->warmupCache, array_flip( $keysGet ) );
295 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) ); // keys left to fetch
296 } else {
297 $wrappedValues = [];
299 $wrappedValues += $this->cache->getMulti( $keysGet );
300 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
301 $now = microtime( true );
303 // Collect timestamps from all "check" keys
304 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
305 $purgeValuesByKey = [];
306 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
307 $purgeValuesByKey[$cacheKey] =
308 $this->processCheckKeys( $checks, $wrappedValues, $now );
311 // Get the main cache value for each key and validate them
312 foreach ( $valueKeys as $vKey ) {
313 if ( !isset( $wrappedValues[$vKey] ) ) {
314 continue; // not found
317 $key = substr( $vKey, $vPrefixLen ); // unprefix
319 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
320 if ( $value !== false ) {
321 $result[$key] = $value;
323 // Force dependant keys to be invalid for a while after purging
324 // to reduce race conditions involving stale data getting cached
325 $purgeValues = $purgeValuesForAll;
326 if ( isset( $purgeValuesByKey[$key] ) ) {
327 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
329 foreach ( $purgeValues as $purge ) {
330 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
331 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
332 // How long ago this value was expired by *this* check key
333 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
334 // How long ago this value was expired by *any* known check key
335 $curTTL = min( $curTTL, $ago );
339 $curTTLs[$key] = $curTTL;
340 $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
343 return $result;
347 * @since 1.27
348 * @param array $timeKeys List of prefixed time check keys
349 * @param array $wrappedValues
350 * @param float $now
351 * @return array List of purge value arrays
353 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
354 $purgeValues = [];
355 foreach ( $timeKeys as $timeKey ) {
356 $purge = isset( $wrappedValues[$timeKey] )
357 ? self::parsePurgeValue( $wrappedValues[$timeKey] )
358 : false;
359 if ( $purge === false ) {
360 // Key is not set or invalid; regenerate
361 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
362 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
363 $purge = self::parsePurgeValue( $newVal );
365 $purgeValues[] = $purge;
367 return $purgeValues;
371 * Set the value of a key in cache
373 * Simply calling this method when source data changes is not valid because
374 * the changes do not replicate to the other WAN sites. In that case, delete()
375 * should be used instead. This method is intended for use on cache misses.
377 * If the data was read from a snapshot-isolated transactions (e.g. the default
378 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
379 * - a) T1 starts
380 * - b) T2 updates a row, calls delete(), and commits
381 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
382 * - d) T1 reads the row and calls set() due to a cache miss
383 * - e) Stale value is stuck in cache
385 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
387 * Example usage:
388 * @code
389 * $dbr = wfGetDB( DB_REPLICA );
390 * $setOpts = Database::getCacheSetOptions( $dbr );
391 * // Fetch the row from the DB
392 * $row = $dbr->selectRow( ... );
393 * $key = $cache->makeKey( 'building', $buildingId );
394 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
395 * @endcode
397 * @param string $key Cache key
398 * @param mixed $value
399 * @param integer $ttl Seconds to live. Special values are:
400 * - WANObjectCache::TTL_INDEFINITE: Cache forever
401 * @param array $opts Options map:
402 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
403 * before the data was read or, if applicable, the replica DB lag before
404 * the snapshot-isolated transaction the data was read from started.
405 * Use false to indicate that replication is not running.
406 * Default: 0 seconds
407 * - since : UNIX timestamp of the data in $value. Typically, this is either
408 * the current time the data was read or (if applicable) the time when
409 * the snapshot-isolated transaction the data was read from started.
410 * Default: 0 seconds
411 * - pending : Whether this data is possibly from an uncommitted write transaction.
412 * Generally, other threads should not see values from the future and
413 * they certainly should not see ones that ended up getting rolled back.
414 * Default: false
415 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
416 * with this TTL and flag it as stale. This is only useful if the reads for
417 * this key use getWithSetCallback() with "lockTSE" set.
418 * Default: WANObjectCache::TSE_NONE
419 * - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
420 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
421 * will call the regeneration callback in such cases, passing in the old value
422 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
423 * on the old value's as-of time when it is verified as still being correct.
424 * Default: 0.
425 * @note Options added in 1.28: staleTTL
426 * @return bool Success
428 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
429 $now = microtime( true );
430 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
431 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
432 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
433 $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : 0;
435 // Do not cache potentially uncommitted data as it might get rolled back
436 if ( !empty( $opts['pending'] ) ) {
437 $this->logger->info( "Rejected set() for $key due to pending writes." );
439 return true; // no-op the write for being unsafe
442 $wrapExtra = []; // additional wrapped value fields
443 // Check if there's a risk of writing stale data after the purge tombstone expired
444 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
445 // Case A: read lag with "lockTSE"; save but record value as stale
446 if ( $lockTSE >= 0 ) {
447 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
448 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
449 // Case B: any long-running transaction; ignore this set()
450 } elseif ( $age > self::MAX_READ_LAG ) {
451 $this->logger->info( "Rejected set() for $key due to snapshot lag." );
453 return true; // no-op the write for being unsafe
454 // Case C: high replication lag; lower TTL instead of ignoring all set()s
455 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
456 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
457 $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
458 // Case D: medium length request with medium replication lag; ignore this set()
459 } else {
460 $this->logger->info( "Rejected set() for $key due to high read lag." );
462 return true; // no-op the write for being unsafe
466 // Wrap that value with time/TTL/version metadata
467 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
469 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
470 return ( is_string( $cWrapped ) )
471 ? false // key is tombstoned; do nothing
472 : $wrapped;
475 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl + $staleTTL, 1 );
479 * Purge a key from all datacenters
481 * This should only be called when the underlying data (being cached)
482 * changes in a significant way. This deletes the key and starts a hold-off
483 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
484 * This is done to avoid the following race condition:
485 * - a) Some DB data changes and delete() is called on a corresponding key
486 * - b) A request refills the key with a stale value from a lagged DB
487 * - c) The stale value is stuck there until the key is expired/evicted
489 * This is implemented by storing a special "tombstone" value at the cache
490 * key that this class recognizes; get() calls will return false for the key
491 * and any set() calls will refuse to replace tombstone values at the key.
492 * For this to always avoid stale value writes, the following must hold:
493 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
494 * - b) If lag is higher, the DB will have gone into read-only mode already
496 * Note that set() can also be lag-aware and lower the TTL if it's high.
498 * When using potentially long-running ACID transactions, a good pattern is
499 * to use a pre-commit hook to issue the delete. This means that immediately
500 * after commit, callers will see the tombstone in cache upon purge relay.
501 * It also avoids the following race condition:
502 * - a) T1 begins, changes a row, and calls delete()
503 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
504 * - c) T2 starts, reads the row and calls set() due to a cache miss
505 * - d) T1 finally commits
506 * - e) Stale value is stuck in cache
508 * Example usage:
509 * @code
510 * $dbw->startAtomic( __METHOD__ ); // start of request
511 * ... <execute some stuff> ...
512 * // Update the row in the DB
513 * $dbw->update( ... );
514 * $key = $cache->makeKey( 'homes', $homeId );
515 * // Purge the corresponding cache entry just before committing
516 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
517 * $cache->delete( $key );
518 * } );
519 * ... <execute some stuff> ...
520 * $dbw->endAtomic( __METHOD__ ); // end of request
521 * @endcode
523 * The $ttl parameter can be used when purging values that have not actually changed
524 * recently. For example, a cleanup script to purge cache entries does not really need
525 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
526 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
528 * If called twice on the same key, then the last hold-off TTL takes precedence. For
529 * idempotence, the $ttl should not vary for different delete() calls on the same key.
531 * @param string $key Cache key
532 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
533 * @return bool True if the item was purged or not found, false on failure
535 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
536 $key = self::VALUE_KEY_PREFIX . $key;
538 if ( $ttl <= 0 ) {
539 // Publish the purge to all datacenters
540 $ok = $this->relayDelete( $key );
541 } else {
542 // Publish the purge to all datacenters
543 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE );
546 return $ok;
550 * Fetch the value of a timestamp "check" key
552 * The key will be *initialized* to the current time if not set,
553 * so only call this method if this behavior is actually desired
555 * The timestamp can be used to check whether a cached value is valid.
556 * Callers should not assume that this returns the same timestamp in
557 * all datacenters due to relay delays.
559 * The level of staleness can roughly be estimated from this key, but
560 * if the key was evicted from cache, such calculations may show the
561 * time since expiry as ~0 seconds.
563 * Note that "check" keys won't collide with other regular keys.
565 * @param string $key
566 * @return float UNIX timestamp of the check key
568 final public function getCheckKeyTime( $key ) {
569 $key = self::TIME_KEY_PREFIX . $key;
571 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
572 if ( $purge !== false ) {
573 $time = $purge[self::FLD_TIME];
574 } else {
575 // Casting assures identical floats for the next getCheckKeyTime() calls
576 $now = (string)microtime( true );
577 $this->cache->add( $key,
578 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
579 self::CHECK_KEY_TTL
581 $time = (float)$now;
584 return $time;
588 * Purge a "check" key from all datacenters, invalidating keys that use it
590 * This should only be called when the underlying data (being cached)
591 * changes in a significant way, and it is impractical to call delete()
592 * on all keys that should be changed. When get() is called on those
593 * keys, the relevant "check" keys must be supplied for this to work.
595 * The "check" key essentially represents a last-modified field.
596 * When touched, the field will be updated on all cache servers.
597 * Keys using it via get(), getMulti(), or getWithSetCallback() will
598 * be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
599 * by those methods to avoid race conditions where dependent keys get updated
600 * with stale values (e.g. from a DB replica DB).
602 * This is typically useful for keys with hardcoded names or in some cases
603 * dynamically generated names where a low number of combinations exist.
604 * When a few important keys get a large number of hits, a high cache
605 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
606 * method is less appropriate in such cases since the "time since expiry"
607 * cannot be inferred, causing any get() after the reset to treat the key
608 * as being "hot", resulting in more stale value usage.
610 * Note that "check" keys won't collide with other regular keys.
612 * @see WANObjectCache::get()
613 * @see WANObjectCache::getWithSetCallback()
614 * @see WANObjectCache::resetCheckKey()
616 * @param string $key Cache key
617 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
618 * @return bool True if the item was purged or not found, false on failure
620 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
621 // Publish the purge to all datacenters
622 return $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
626 * Delete a "check" key from all datacenters, invalidating keys that use it
628 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
629 * or getWithSetCallback() will be invalidated. The differences are:
630 * - a) The "check" key will be deleted from all caches and lazily
631 * re-initialized when accessed (rather than set everywhere)
632 * - b) Thus, dependent keys will be known to be invalid, but not
633 * for how long (they are treated as "just" purged), which
634 * effects any lockTSE logic in getWithSetCallback()
635 * - c) Since "check" keys are initialized only on the server the key hashes
636 * to, any temporary ejection of that server will cause the value to be
637 * seen as purged as a new server will initialize the "check" key.
639 * The advantage is that this does not place high TTL keys on every cache
640 * server, making it better for code that will cache many different keys
641 * and either does not use lockTSE or uses a low enough TTL anyway.
643 * This is typically useful for keys with dynamically generated names
644 * where a high number of combinations exist.
646 * Note that "check" keys won't collide with other regular keys.
648 * @see WANObjectCache::get()
649 * @see WANObjectCache::getWithSetCallback()
650 * @see WANObjectCache::touchCheckKey()
652 * @param string $key Cache key
653 * @return bool True if the item was purged or not found, false on failure
655 final public function resetCheckKey( $key ) {
656 // Publish the purge to all datacenters
657 return $this->relayDelete( self::TIME_KEY_PREFIX . $key );
661 * Method to fetch/regenerate cache keys
663 * On cache miss, the key will be set to the callback result via set()
664 * (unless the callback returns false) and that result will be returned.
665 * The arguments supplied to the callback are:
666 * - $oldValue : current cache value or false if not present
667 * - &$ttl : a reference to the TTL which can be altered
668 * - &$setOpts : a reference to options for set() which can be altered
669 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
671 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
672 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
673 * value, but it can be used to maintain "most recent X" values that come from time or
674 * sequence based source data, provided that the "as of" id/time is tracked. Note that
675 * preemptive regeneration and $checkKeys can result in a non-false current value.
677 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
678 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
679 * regeneration will automatically be triggered using the callback.
681 * The simplest way to avoid stampedes for hot keys is to use
682 * the 'lockTSE' option in $opts. If cache purges are needed, also:
683 * - a) Pass $key into $checkKeys
684 * - b) Use touchCheckKey( $key ) instead of delete( $key )
686 * Example usage (typical key):
687 * @code
688 * $catInfo = $cache->getWithSetCallback(
689 * // Key to store the cached value under
690 * $cache->makeKey( 'cat-attributes', $catId ),
691 * // Time-to-live (in seconds)
692 * $cache::TTL_MINUTE,
693 * // Function that derives the new key value
694 * function ( $oldValue, &$ttl, array &$setOpts ) {
695 * $dbr = wfGetDB( DB_REPLICA );
696 * // Account for any snapshot/replica DB lag
697 * $setOpts += Database::getCacheSetOptions( $dbr );
699 * return $dbr->selectRow( ... );
701 * );
702 * @endcode
704 * Example usage (key that is expensive and hot):
705 * @code
706 * $catConfig = $cache->getWithSetCallback(
707 * // Key to store the cached value under
708 * $cache->makeKey( 'site-cat-config' ),
709 * // Time-to-live (in seconds)
710 * $cache::TTL_DAY,
711 * // Function that derives the new key value
712 * function ( $oldValue, &$ttl, array &$setOpts ) {
713 * $dbr = wfGetDB( DB_REPLICA );
714 * // Account for any snapshot/replica DB lag
715 * $setOpts += Database::getCacheSetOptions( $dbr );
717 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
718 * },
720 * // Calling touchCheckKey() on this key invalidates the cache
721 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
722 * // Try to only let one datacenter thread manage cache updates at a time
723 * 'lockTSE' => 30,
724 * // Avoid querying cache servers multiple times in a web request
725 * 'pcTTL' => $cache::TTL_PROC_LONG
727 * );
728 * @endcode
730 * Example usage (key with dynamic dependencies):
731 * @code
732 * $catState = $cache->getWithSetCallback(
733 * // Key to store the cached value under
734 * $cache->makeKey( 'cat-state', $cat->getId() ),
735 * // Time-to-live (seconds)
736 * $cache::TTL_HOUR,
737 * // Function that derives the new key value
738 * function ( $oldValue, &$ttl, array &$setOpts ) {
739 * // Determine new value from the DB
740 * $dbr = wfGetDB( DB_REPLICA );
741 * // Account for any snapshot/replica DB lag
742 * $setOpts += Database::getCacheSetOptions( $dbr );
744 * return CatState::newFromResults( $dbr->select( ... ) );
745 * },
747 * // The "check" keys that represent things the value depends on;
748 * // Calling touchCheckKey() on any of them invalidates the cache
749 * 'checkKeys' => [
750 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
751 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
752 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
755 * );
756 * @endcode
758 * Example usage (hot key holding most recent 100 events):
759 * @code
760 * $lastCatActions = $cache->getWithSetCallback(
761 * // Key to store the cached value under
762 * $cache->makeKey( 'cat-last-actions', 100 ),
763 * // Time-to-live (in seconds)
764 * 10,
765 * // Function that derives the new key value
766 * function ( $oldValue, &$ttl, array &$setOpts ) {
767 * $dbr = wfGetDB( DB_REPLICA );
768 * // Account for any snapshot/replica DB lag
769 * $setOpts += Database::getCacheSetOptions( $dbr );
771 * // Start off with the last cached list
772 * $list = $oldValue ?: [];
773 * // Fetch the last 100 relevant rows in descending order;
774 * // only fetch rows newer than $list[0] to reduce scanning
775 * $rows = iterator_to_array( $dbr->select( ... ) );
776 * // Merge them and get the new "last 100" rows
777 * return array_slice( array_merge( $new, $list ), 0, 100 );
778 * },
780 * // Try to only let one datacenter thread manage cache updates at a time
781 * 'lockTSE' => 30,
782 * // Use a magic value when no cache value is ready rather than stampeding
783 * 'busyValue' => 'computing'
785 * );
786 * @endcode
788 * @see WANObjectCache::get()
789 * @see WANObjectCache::set()
791 * @param string $key Cache key
792 * @param integer $ttl Seconds to live for key updates. Special values are:
793 * - WANObjectCache::TTL_INDEFINITE: Cache forever
794 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
795 * @param callable $callback Value generation function
796 * @param array $opts Options map:
797 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
798 * touchCheckKey() or resetCheckKey() is called on any of these keys.
799 * Default: [].
800 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
801 * ago, then try to have a single thread handle cache regeneration at any given time.
802 * Other threads will try to use stale values if possible. If, on miss, the time since
803 * expiration is low, the assumption is that the key is hot and that a stampede is worth
804 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
805 * higher this is set, the higher the worst-case staleness can be.
806 * Use WANObjectCache::TSE_NONE to disable this logic.
807 * Default: WANObjectCache::TSE_NONE.
808 * - busyValue: If no value exists and another thread is currently regenerating it, use this
809 * as a fallback value (or a callback to generate such a value). This assures that cache
810 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
811 * against cache regeneration becoming very slow for some reason (greater than the TTL).
812 * Default: null.
813 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
814 * network I/O when a key is read several times. This will not cache when the callback
815 * returns false, however. Note that any purges will not be seen while process cached;
816 * since the callback should use replica DBs and they may be lagged or have snapshot
817 * isolation anyway, this should not typically matter.
818 * Default: WANObjectCache::TTL_UNCACHEABLE.
819 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
820 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
821 * large values, small yet numerous values, or some values with a high cost of eviction.
822 * It is generally preferable to use a class constant when setting this value.
823 * This has no effect unless pcTTL is used.
824 * Default: WANObjectCache::PC_PRIMARY.
825 * - version: Integer version number. This allows for callers to make breaking changes to
826 * how values are stored while maintaining compatability and correct cache purges. New
827 * versions are stored alongside older versions concurrently. Avoid storing class objects
828 * however, as this reduces compatibility (due to serialization).
829 * Default: null.
830 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
831 * This is useful if the source of a key is suspected of having possibly changed
832 * recently, and the caller wants any such changes to be reflected.
833 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
834 * - hotTTR: Expected time-till-refresh for keys that average ~1 hit/second.
835 * This should be greater than "ageNew". Keys with higher hit rates will regenerate
836 * more often. This is useful when a popular key is changed but the cache purge was
837 * delayed or lost. Seldom used keys are rarely affected by this setting, unless an
838 * extremely low "hotTTR" value is passed in.
839 * Default: WANObjectCache::HOT_TTR.
840 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
841 * than this. It becomes more likely over time, becoming certain once the key is expired.
842 * Default: WANObjectCache::LOW_TTL.
843 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
844 * Default: WANObjectCache::AGE_NEW.
845 * @return mixed Value found or written to the key
846 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
847 * @note Callable type hints are not used to avoid class-autoloading
849 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
850 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
852 // Try the process cache if enabled and the cache callback is not within a cache callback.
853 // Process cache use in nested callbacks is not lag-safe with regard to HOLDOFF_TTL since
854 // the in-memory value is further lagged than the shared one since it uses a blind TTL.
855 if ( $pcTTL >= 0 && $this->callbackDepth == 0 ) {
856 $group = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY;
857 $procCache = $this->getProcessCache( $group );
858 $value = $procCache->get( $key );
859 } else {
860 $procCache = false;
861 $value = false;
864 if ( $value === false ) {
865 // Fetch the value over the network
866 if ( isset( $opts['version'] ) ) {
867 $version = $opts['version'];
868 $asOf = null;
869 $cur = $this->doGetWithSetCallback(
870 $key,
871 $ttl,
872 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
873 use ( $callback, $version ) {
874 if ( is_array( $oldValue )
875 && array_key_exists( self::VFLD_DATA, $oldValue )
877 $oldData = $oldValue[self::VFLD_DATA];
878 } else {
879 // VFLD_DATA is not set if an old, unversioned, key is present
880 $oldData = false;
883 return [
884 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
885 self::VFLD_VERSION => $version
888 $opts,
889 $asOf
891 if ( $cur[self::VFLD_VERSION] === $version ) {
892 // Value created or existed before with version; use it
893 $value = $cur[self::VFLD_DATA];
894 } else {
895 // Value existed before with a different version; use variant key.
896 // Reflect purges to $key by requiring that this key value be newer.
897 $value = $this->doGetWithSetCallback(
898 'cache-variant:' . md5( $key ) . ":$version",
899 $ttl,
900 $callback,
901 // Regenerate value if not newer than $key
902 [ 'version' => null, 'minAsOf' => $asOf ] + $opts
905 } else {
906 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
909 // Update the process cache if enabled
910 if ( $procCache && $value !== false ) {
911 $procCache->set( $key, $value, $pcTTL );
915 return $value;
919 * Do the actual I/O for getWithSetCallback() when needed
921 * @see WANObjectCache::getWithSetCallback()
923 * @param string $key
924 * @param integer $ttl
925 * @param callback $callback
926 * @param array $opts Options map for getWithSetCallback()
927 * @param float &$asOf Cache generation timestamp of returned value [returned]
928 * @return mixed
929 * @note Callable type hints are not used to avoid class-autoloading
931 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
932 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
933 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
934 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
935 $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
936 $popWindow = isset( $opts['hotTTR'] ) ? $opts['hotTTR'] : self::HOT_TTR;
937 $ageNew = isset( $opts['ageNew'] ) ? $opts['ageNew'] : self::AGE_NEW;
938 $minTime = isset( $opts['minAsOf'] ) ? $opts['minAsOf'] : self::MIN_TIMESTAMP_NONE;
939 $versioned = isset( $opts['version'] );
941 // Get the current key value
942 $curTTL = null;
943 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
944 $value = $cValue; // return value
946 $preCallbackTime = microtime( true );
947 // Determine if a cached value regeneration is needed or desired
948 if ( $value !== false
949 && $curTTL > 0
950 && $this->isValid( $value, $versioned, $asOf, $minTime )
951 && !$this->worthRefreshExpiring( $curTTL, $lowTTL )
952 && !$this->worthRefreshPopular( $asOf, $ageNew, $popWindow, $preCallbackTime )
954 return $value;
957 // A deleted key with a negative TTL left must be tombstoned
958 $isTombstone = ( $curTTL !== null && $value === false );
959 // Assume a key is hot if requested soon after invalidation
960 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
961 // Use the mutex if there is no value and a busy fallback is given
962 $checkBusy = ( $busyValue !== null && $value === false );
963 // Decide whether a single thread should handle regenerations.
964 // This avoids stampedes when $checkKeys are bumped and when preemptive
965 // renegerations take too long. It also reduces regenerations while $key
966 // is tombstoned. This balances cache freshness with avoiding DB load.
967 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
969 $lockAcquired = false;
970 if ( $useMutex ) {
971 // Acquire a datacenter-local non-blocking lock
972 if ( $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
973 // Lock acquired; this thread should update the key
974 $lockAcquired = true;
975 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
976 // If it cannot be acquired; then the stale value can be used
977 return $value;
978 } else {
979 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
980 // For hot keys, either another thread has the lock or the lock failed;
981 // use the INTERIM value from the last thread that regenerated it.
982 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
983 list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
984 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
985 $asOf = $wrapped[self::FLD_TIME];
987 return $value;
989 // Use the busy fallback value if nothing else
990 if ( $busyValue !== null ) {
991 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
996 if ( !is_callable( $callback ) ) {
997 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
1000 // Generate the new value from the callback...
1001 $setOpts = [];
1002 ++$this->callbackDepth;
1003 try {
1004 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
1005 } finally {
1006 --$this->callbackDepth;
1008 // When delete() is called, writes are write-holed by the tombstone,
1009 // so use a special INTERIM key to pass the new value around threads.
1010 if ( ( $isTombstone && $lockTSE > 0 ) && $value !== false && $ttl >= 0 ) {
1011 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
1012 $newAsOf = microtime( true );
1013 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
1014 // Avoid using set() to avoid pointless mcrouter broadcasting
1015 $this->cache->merge(
1016 self::INTERIM_KEY_PREFIX . $key,
1017 function () use ( $wrapped ) {
1018 return $wrapped;
1020 $tempTTL,
1025 if ( $value !== false && $ttl >= 0 ) {
1026 $setOpts['lockTSE'] = $lockTSE;
1027 // Use best known "since" timestamp if not provided
1028 $setOpts += [ 'since' => $preCallbackTime ];
1029 // Update the cache; this will fail if the key is tombstoned
1030 $this->set( $key, $value, $ttl, $setOpts );
1033 if ( $lockAcquired ) {
1034 // Avoid using delete() to avoid pointless mcrouter broadcasting
1035 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, 1 );
1038 return $value;
1042 * Method to fetch/regenerate multiple cache keys at once
1044 * This works the same as getWithSetCallback() except:
1045 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1046 * - b) The $callback argument expects a callback taking the following arguments:
1047 * - $id: ID of an entity to query
1048 * - $oldValue : the prior cache value or false if none was present
1049 * - &$ttl : a reference to the new value TTL in seconds
1050 * - &$setOpts : a reference to options for set() which can be altered
1051 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present
1052 * Aside from the additional $id argument, the other arguments function the same
1053 * way they do in getWithSetCallback().
1054 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1056 * @see WANObjectCache::getWithSetCallback()
1058 * Example usage:
1059 * @code
1060 * $rows = $cache->getMultiWithSetCallback(
1061 * // Map of cache keys to entity IDs
1062 * $cache->makeMultiKeys(
1063 * $this->fileVersionIds(),
1064 * function ( $id, WANObjectCache $cache ) {
1065 * return $cache->makeKey( 'file-version', $id );
1067 * ),
1068 * // Time-to-live (in seconds)
1069 * $cache::TTL_DAY,
1070 * // Function that derives the new key value
1071 * return function ( $id, $oldValue, &$ttl, array &$setOpts ) {
1072 * $dbr = wfGetDB( DB_REPLICA );
1073 * // Account for any snapshot/replica DB lag
1074 * $setOpts += Database::getCacheSetOptions( $dbr );
1076 * // Load the row for this file
1077 * $row = $dbr->selectRow( 'file', '*', [ 'id' => $id ], __METHOD__ );
1079 * return $row ? (array)$row : false;
1080 * },
1082 * // Process cache for 30 seconds
1083 * 'pcTTL' => 30,
1084 * // Use a dedicated 500 item cache (initialized on-the-fly)
1085 * 'pcGroup' => 'file-versions:500'
1087 * );
1088 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1089 * @endcode
1091 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1092 * @param integer $ttl Seconds to live for key updates
1093 * @param callable $callback Callback the yields entity regeneration callbacks
1094 * @param array $opts Options map
1095 * @return array Map of (cache key => value) in the same order as $keyedIds
1096 * @since 1.28
1098 final public function getMultiWithSetCallback(
1099 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1101 $keysWarmUp = iterator_to_array( $keyedIds, true );
1102 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
1103 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
1104 if ( is_int( $i ) ) {
1105 $keysWarmUp[] = $checkKeyOrKeys;
1106 } else {
1107 $keysWarmUp = array_merge( $keysWarmUp, $checkKeyOrKeys );
1111 $this->warmupCache = $this->cache->getMulti( $keysWarmUp );
1112 $this->warmupCache += array_fill_keys( $keysWarmUp, false );
1114 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1115 $id = null;
1116 $func = function ( $oldValue, &$ttl, array $setOpts, $oldAsOf ) use ( $callback, &$id ) {
1117 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1120 $values = [];
1121 foreach ( $keyedIds as $key => $id ) {
1122 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1125 $this->warmupCache = [];
1127 return $values;
1131 * @see BagOStuff::makeKey()
1132 * @param string ... Key component
1133 * @return string
1134 * @since 1.27
1136 public function makeKey() {
1137 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1141 * @see BagOStuff::makeGlobalKey()
1142 * @param string ... Key component
1143 * @return string
1144 * @since 1.27
1146 public function makeGlobalKey() {
1147 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1151 * @param array $entities List of entity IDs
1152 * @param callable $keyFunc Callback yielding a key from (entity ID, this WANObjectCache)
1153 * @return ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
1154 * @since 1.28
1156 public function makeMultiKeys( array $entities, callable $keyFunc ) {
1157 $map = [];
1158 foreach ( $entities as $entity ) {
1159 $map[$keyFunc( $entity, $this )] = $entity;
1162 return new ArrayIterator( $map );
1166 * Get the "last error" registered; clearLastError() should be called manually
1167 * @return int ERR_* class constant for the "last error" registry
1169 final public function getLastError() {
1170 if ( $this->lastRelayError ) {
1171 // If the cache and the relayer failed, focus on the latter.
1172 // An update not making it to the relayer means it won't show up
1173 // in other DCs (nor will consistent re-hashing see up-to-date values).
1174 // On the other hand, if just the cache update failed, then it should
1175 // eventually be applied by the relayer.
1176 return $this->lastRelayError;
1179 $code = $this->cache->getLastError();
1180 switch ( $code ) {
1181 case BagOStuff::ERR_NONE:
1182 return self::ERR_NONE;
1183 case BagOStuff::ERR_NO_RESPONSE:
1184 return self::ERR_NO_RESPONSE;
1185 case BagOStuff::ERR_UNREACHABLE:
1186 return self::ERR_UNREACHABLE;
1187 default:
1188 return self::ERR_UNEXPECTED;
1193 * Clear the "last error" registry
1195 final public function clearLastError() {
1196 $this->cache->clearLastError();
1197 $this->lastRelayError = self::ERR_NONE;
1201 * Clear the in-process caches; useful for testing
1203 * @since 1.27
1205 public function clearProcessCache() {
1206 $this->processCaches = [];
1210 * @param integer $flag ATTR_* class constant
1211 * @return integer QOS_* class constant
1212 * @since 1.28
1214 public function getQoS( $flag ) {
1215 return $this->cache->getQoS( $flag );
1219 * Get a TTL that is higher for objects that have not changed recently
1221 * This is useful for keys that get explicit purges and DB or purge relay
1222 * lag is a potential concern (especially how it interacts with CDN cache)
1224 * Example usage:
1225 * @code
1226 * // Last-modified time of page
1227 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1228 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1229 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1230 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1231 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1232 * @endcode
1234 * @param integer|float $mtime UNIX timestamp
1235 * @param integer $maxTTL Maximum TTL (seconds)
1236 * @param integer $minTTL Minimum TTL (seconds); Default: 30
1237 * @param float $factor Value in the range (0,1); Default: .2
1238 * @return integer Adaptive TTL
1239 * @since 1.28
1241 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = .2 ) {
1242 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
1243 $mtime = (int)$mtime; // handle fractional seconds and string integers
1246 if ( !is_int( $mtime ) || $mtime <= 0 ) {
1247 return $minTTL; // no last-modified time provided
1250 $age = time() - $mtime;
1252 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1256 * Do the actual async bus purge of a key
1258 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1260 * @param string $key Cache key
1261 * @param integer $ttl How long to keep the tombstone [seconds]
1262 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1263 * @return bool Success
1265 protected function relayPurge( $key, $ttl, $holdoff ) {
1266 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1267 // This handles the mcrouter and the single-DC case
1268 $ok = $this->cache->set( $key,
1269 $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
1270 $ttl
1272 } else {
1273 $event = $this->cache->modifySimpleRelayEvent( [
1274 'cmd' => 'set',
1275 'key' => $key,
1276 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1277 'ttl' => max( $ttl, 1 ),
1278 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1279 ] );
1281 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1282 if ( !$ok ) {
1283 $this->lastRelayError = self::ERR_RELAY;
1287 return $ok;
1291 * Do the actual async bus delete of a key
1293 * @param string $key Cache key
1294 * @return bool Success
1296 protected function relayDelete( $key ) {
1297 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1298 // This handles the mcrouter and the single-DC case
1299 $ok = $this->cache->delete( $key );
1300 } else {
1301 $event = $this->cache->modifySimpleRelayEvent( [
1302 'cmd' => 'delete',
1303 'key' => $key,
1304 ] );
1306 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1307 if ( !$ok ) {
1308 $this->lastRelayError = self::ERR_RELAY;
1312 return $ok;
1316 * Check if a key should be regenerated (using random probability)
1318 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
1319 * of returning true increases steadily from 0% to 100% as the $curTTL
1320 * moves from $lowTTL to 0 seconds. This handles widely varying
1321 * levels of cache access traffic.
1323 * @param float $curTTL Approximate TTL left on the key if present
1324 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1325 * @return bool
1327 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1328 if ( $curTTL >= $lowTTL ) {
1329 return false;
1330 } elseif ( $curTTL <= 0 ) {
1331 return true;
1334 $chance = ( 1 - $curTTL / $lowTTL );
1336 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1340 * Check if a key is due for randomized regeneration due to its popularity
1342 * This is used so that popular keys can preemptively refresh themselves for higher
1343 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
1344 * in cache with their high nominal TTL. This means popular keys keep good consistency,
1345 * whether the data changes frequently or not, and long-tail keys get to stay in cache
1346 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
1348 * @param float $asOf UNIX timestamp of the value
1349 * @param integer $ageNew Age of key when this might recommend refreshing (seconds)
1350 * @param integer $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
1351 * @param float $now The current UNIX timestamp
1352 * @return bool
1354 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
1355 $age = $now - $asOf;
1356 $timeOld = $age - $ageNew;
1357 if ( $timeOld <= 0 ) {
1358 return false;
1361 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
1362 // Note that the "expected # of refreshes" for the ramp-up time range is half of what it
1363 // would be if P(refresh) was at its full value during that time range.
1364 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
1365 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1366 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1367 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1368 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
1370 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1371 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
1373 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1377 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1379 * @param array $value
1380 * @param bool $versioned
1381 * @param float $asOf The time $value was generated
1382 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1383 * @return bool
1385 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1386 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1387 return false;
1388 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1389 return false;
1392 return true;
1396 * Do not use this method outside WANObjectCache
1398 * @param mixed $value
1399 * @param integer $ttl [0=forever]
1400 * @param float $now Unix Current timestamp just before calling set()
1401 * @return array
1403 protected function wrap( $value, $ttl, $now ) {
1404 return [
1405 self::FLD_VERSION => self::VERSION,
1406 self::FLD_VALUE => $value,
1407 self::FLD_TTL => $ttl,
1408 self::FLD_TIME => $now
1413 * Do not use this method outside WANObjectCache
1415 * @param array|string|bool $wrapped
1416 * @param float $now Unix Current timestamp (preferrably pre-query)
1417 * @return array (mixed; false if absent/invalid, current time left)
1419 protected function unwrap( $wrapped, $now ) {
1420 // Check if the value is a tombstone
1421 $purge = self::parsePurgeValue( $wrapped );
1422 if ( $purge !== false ) {
1423 // Purged values should always have a negative current $ttl
1424 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1425 return [ false, $curTTL ];
1428 if ( !is_array( $wrapped ) // not found
1429 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1430 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1432 return [ false, null ];
1435 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1436 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1437 // Treat as expired, with the cache time as the expiration
1438 $age = $now - $wrapped[self::FLD_TIME];
1439 $curTTL = min( -$age, self::TINY_NEGATIVE );
1440 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1441 // Get the approximate time left on the key
1442 $age = $now - $wrapped[self::FLD_TIME];
1443 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1444 } else {
1445 // Key had no TTL, so the time left is unbounded
1446 $curTTL = INF;
1449 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1453 * @param array $keys
1454 * @param string $prefix
1455 * @return string[]
1457 protected static function prefixCacheKeys( array $keys, $prefix ) {
1458 $res = [];
1459 foreach ( $keys as $key ) {
1460 $res[] = $prefix . $key;
1463 return $res;
1467 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1468 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1469 * or false if value isn't a valid purge value
1471 protected static function parsePurgeValue( $value ) {
1472 if ( !is_string( $value ) ) {
1473 return false;
1475 $segments = explode( ':', $value, 3 );
1476 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1477 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1479 return false;
1481 if ( !isset( $segments[2] ) ) {
1482 // Back-compat with old purge values without holdoff
1483 $segments[2] = self::HOLDOFF_TTL;
1485 return [
1486 self::FLD_TIME => (float)$segments[1],
1487 self::FLD_HOLDOFF => (int)$segments[2],
1492 * @param float $timestamp
1493 * @param int $holdoff In seconds
1494 * @return string Wrapped purge value
1496 protected function makePurgeValue( $timestamp, $holdoff ) {
1497 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1501 * @param string $group
1502 * @return HashBagOStuff
1504 protected function getProcessCache( $group ) {
1505 if ( !isset( $this->processCaches[$group] ) ) {
1506 list( , $n ) = explode( ':', $group );
1507 $this->processCaches[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
1510 return $this->processCaches[$group];