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
20 * @author Aaron Schulz
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 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
76 class WANObjectCache
implements IExpiringStore
, LoggerAwareInterface
{
77 /** @var BagOStuff The local datacenter 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 */
88 /** @var int ERR_* constant for the "last error" registry */
89 protected $lastRelayError = self
::ERR_NONE
;
91 /** Max time expected to pass between delete() and DB commit finishing */
92 const MAX_COMMIT_DELAY
= 3;
93 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
94 const MAX_READ_LAG
= 7;
95 /** Seconds to tombstone keys on delete() */
96 const HOLDOFF_TTL
= 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
98 /** Seconds to keep dependency purge keys around */
99 const CHECK_KEY_TTL
= self
::TTL_YEAR
;
100 /** Seconds to keep lock keys around */
102 /** Default remaining TTL at which to consider pre-emptive regeneration */
104 /** Default time-since-expiry on a miss that makes a key "hot" */
107 /** Never consider performing "popularity" refreshes until a key reaches this age */
109 /** The time length of the "popularity" refresh window for hot keys */
111 /** Hits/second for a refresh to be expected within the "popularity" window */
112 const HIT_RATE_HIGH
= 1;
113 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
114 const RAMPUP_TTL
= 30;
116 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
117 const TTL_UNCACHEABLE
= -1;
118 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
120 /** Max TTL to store keys when a data sourced is lagged */
121 const TTL_LAGGED
= 30;
122 /** Idiom for delete() for "no hold-off" */
123 const HOLDOFF_NONE
= 0;
124 /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
125 const MIN_TIMESTAMP_NONE
= 0.0;
127 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
128 const TINY_NEGATIVE
= -0.000001;
130 /** Cache format version number */
133 const FLD_VERSION
= 0; // key to cache version number
134 const FLD_VALUE
= 1; // key to the cached value
135 const FLD_TTL
= 2; // key to the original TTL
136 const FLD_TIME
= 3; // key to the cache time
137 const FLD_FLAGS
= 4; // key to the flags bitfield
138 const FLD_HOLDOFF
= 5; // key to any hold-off TTL
140 /** @var integer Treat this value as expired-on-arrival */
143 const ERR_NONE
= 0; // no error
144 const ERR_NO_RESPONSE
= 1; // no response
145 const ERR_UNREACHABLE
= 2; // can't connect
146 const ERR_UNEXPECTED
= 3; // response gave some error
147 const ERR_RELAY
= 4; // relay broadcast failed
149 const VALUE_KEY_PREFIX
= 'WANCache:v:';
150 const INTERIM_KEY_PREFIX
= 'WANCache:i:';
151 const TIME_KEY_PREFIX
= 'WANCache:t:';
152 const MUTEX_KEY_PREFIX
= 'WANCache:m:';
154 const PURGE_VAL_PREFIX
= 'PURGED:';
156 const VFLD_DATA
= 'WOC:d'; // key to the value of versioned data
157 const VFLD_VERSION
= 'WOC:v'; // key to the version of the value present
159 const PC_PRIMARY
= 'primary:1000'; // process cache name and max key count
161 const DEFAULT_PURGE_CHANNEL
= 'wancache-purge';
164 * @param array $params
165 * - cache : BagOStuff object for a persistent cache
166 * - channels : Map of (action => channel string). Actions include "purge".
167 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
168 * - logger : LoggerInterface object
170 public function __construct( array $params ) {
171 $this->cache
= $params['cache'];
172 $this->purgeChannel
= isset( $params['channels']['purge'] )
173 ?
$params['channels']['purge']
174 : self
::DEFAULT_PURGE_CHANNEL
;
175 $this->purgeRelayer
= isset( $params['relayers']['purge'] )
176 ?
$params['relayers']['purge']
177 : new EventRelayerNull( [] );
178 $this->setLogger( isset( $params['logger'] ) ?
$params['logger'] : new NullLogger() );
181 public function setLogger( LoggerInterface
$logger ) {
182 $this->logger
= $logger;
186 * Get an instance that wraps EmptyBagOStuff
188 * @return WANObjectCache
190 public static function newEmpty() {
192 'cache' => new EmptyBagOStuff(),
194 'relayer' => new EventRelayerNull( [] )
199 * Fetch the value of a key from cache
201 * If supplied, $curTTL is set to the remaining TTL (current time left):
202 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
203 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
204 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
205 * - d) null; if $key does not exist and is not tombstoned
207 * If a key is tombstoned, $curTTL will reflect the time since delete().
209 * The timestamp of $key will be checked against the last-purge timestamp
210 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
211 * initialized to the current timestamp. If any of $checkKeys have a timestamp
212 * greater than that of $key, then $curTTL will reflect how long ago $key
213 * became invalid. Callers can use $curTTL to know when the value is stale.
214 * The $checkKeys parameter allow mass invalidations by updating a single key:
215 * - a) Each "check" key represents "last purged" of some source data
216 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
217 * - c) When the source data that "check" keys represent changes,
218 * the touchCheckKey() method is called on them
220 * Source data entities might exists in a DB that uses snapshot isolation
221 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
222 * isolation can largely be maintained by doing the following:
223 * - a) Calling delete() on entity change *and* creation, before DB commit
224 * - b) Keeping transaction duration shorter than delete() hold-off TTL
226 * However, pre-snapshot values might still be seen if an update was made
227 * in a remote datacenter but the purge from delete() didn't relay yet.
229 * Consider using getWithSetCallback() instead of get() and set() cycles.
230 * That method has cache slam avoiding features for hot/expensive keys.
232 * @param string $key Cache key
233 * @param mixed $curTTL Approximate TTL left on the key if present/tombstoned [returned]
234 * @param array $checkKeys List of "check" keys
235 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
236 * @return mixed Value of cache key or false on failure
238 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
241 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
242 $curTTL = isset( $curTTLs[$key] ) ?
$curTTLs[$key] : null;
243 $asOf = isset( $asOfs[$key] ) ?
$asOfs[$key] : null;
245 return isset( $values[$key] ) ?
$values[$key] : false;
249 * Fetch the value of several keys from cache
251 * @see WANObjectCache::get()
253 * @param array $keys List of cache keys
254 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
255 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
256 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
257 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
258 * @return array Map of (key => value) for keys that exist
260 final public function getMulti(
261 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
267 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
268 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
270 $checkKeysForAll = [];
271 $checkKeysByKey = [];
273 foreach ( $checkKeys as $i => $keys ) {
274 $prefixed = self
::prefixCacheKeys( (array)$keys, self
::TIME_KEY_PREFIX
);
275 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
276 // Is this check keys for a specific cache key, or for all keys being fetched?
277 if ( is_int( $i ) ) {
278 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
280 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
281 ?
array_merge( $checkKeysByKey[$i], $prefixed )
286 // Fetch all of the raw values
287 $wrappedValues = $this->cache
->getMulti( array_merge( $valueKeys, $checkKeysFlat ) );
288 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
289 $now = microtime( true );
291 // Collect timestamps from all "check" keys
292 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
293 $purgeValuesByKey = [];
294 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
295 $purgeValuesByKey[$cacheKey] =
296 $this->processCheckKeys( $checks, $wrappedValues, $now );
299 // Get the main cache value for each key and validate them
300 foreach ( $valueKeys as $vKey ) {
301 if ( !isset( $wrappedValues[$vKey] ) ) {
302 continue; // not found
305 $key = substr( $vKey, $vPrefixLen ); // unprefix
307 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
308 if ( $value !== false ) {
309 $result[$key] = $value;
311 // Force dependant keys to be invalid for a while after purging
312 // to reduce race conditions involving stale data getting cached
313 $purgeValues = $purgeValuesForAll;
314 if ( isset( $purgeValuesByKey[$key] ) ) {
315 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
317 foreach ( $purgeValues as $purge ) {
318 $safeTimestamp = $purge[self
::FLD_TIME
] +
$purge[self
::FLD_HOLDOFF
];
319 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
320 // How long ago this value was expired by *this* check key
321 $ago = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
322 // How long ago this value was expired by *any* known check key
323 $curTTL = min( $curTTL, $ago );
327 $curTTLs[$key] = $curTTL;
328 $asOfs[$key] = ( $value !== false ) ?
$wrappedValues[$vKey][self
::FLD_TIME
] : null;
336 * @param array $timeKeys List of prefixed time check keys
337 * @param array $wrappedValues
339 * @return array List of purge value arrays
341 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
343 foreach ( $timeKeys as $timeKey ) {
344 $purge = isset( $wrappedValues[$timeKey] )
345 ? self
::parsePurgeValue( $wrappedValues[$timeKey] )
347 if ( $purge === false ) {
348 // Key is not set or invalid; regenerate
349 $newVal = $this->makePurgeValue( $now, self
::HOLDOFF_TTL
);
350 $this->cache
->add( $timeKey, $newVal, self
::CHECK_KEY_TTL
);
351 $purge = self
::parsePurgeValue( $newVal );
353 $purgeValues[] = $purge;
359 * Set the value of a key in cache
361 * Simply calling this method when source data changes is not valid because
362 * the changes do not replicate to the other WAN sites. In that case, delete()
363 * should be used instead. This method is intended for use on cache misses.
365 * If the data was read from a snapshot-isolated transactions (e.g. the default
366 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
368 * - b) T2 updates a row, calls delete(), and commits
369 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
370 * - d) T1 reads the row and calls set() due to a cache miss
371 * - e) Stale value is stuck in cache
373 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
377 * $dbr = wfGetDB( DB_REPLICA );
378 * $setOpts = Database::getCacheSetOptions( $dbr );
379 * // Fetch the row from the DB
380 * $row = $dbr->selectRow( ... );
381 * $key = $cache->makeKey( 'building', $buildingId );
382 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
385 * @param string $key Cache key
386 * @param mixed $value
387 * @param integer $ttl Seconds to live. Special values are:
388 * - WANObjectCache::TTL_INDEFINITE: Cache forever
389 * @param array $opts Options map:
390 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
391 * before the data was read or, if applicable, the replica DB lag before
392 * the snapshot-isolated transaction the data was read from started.
393 * Use false to indicate that replication is not running.
395 * - since : UNIX timestamp of the data in $value. Typically, this is either
396 * the current time the data was read or (if applicable) the time when
397 * the snapshot-isolated transaction the data was read from started.
399 * - pending : Whether this data is possibly from an uncommitted write transaction.
400 * Generally, other threads should not see values from the future and
401 * they certainly should not see ones that ended up getting rolled back.
403 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
404 * with this TTL and flag it as stale. This is only useful if the reads for
405 * this key use getWithSetCallback() with "lockTSE" set.
406 * Default: WANObjectCache::TSE_NONE
407 * - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
408 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
409 * will call the regeneration callback in such cases, passing in the old value
410 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
411 * on the old value's as-of time when it is verified as still being correct.
413 * @note Options added in 1.28: staleTTL
414 * @return bool Success
416 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
417 $now = microtime( true );
418 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
419 $age = isset( $opts['since'] ) ?
max( 0, $now - $opts['since'] ) : 0;
420 $lag = isset( $opts['lag'] ) ?
$opts['lag'] : 0;
421 $staleTTL = isset( $opts['staleTTL'] ) ?
$opts['staleTTL'] : 0;
423 // Do not cache potentially uncommitted data as it might get rolled back
424 if ( !empty( $opts['pending'] ) ) {
425 $this->logger
->info( "Rejected set() for $key due to pending writes." );
427 return true; // no-op the write for being unsafe
430 $wrapExtra = []; // additional wrapped value fields
431 // Check if there's a risk of writing stale data after the purge tombstone expired
432 if ( $lag === false ||
( $lag +
$age ) > self
::MAX_READ_LAG
) {
433 // Case A: read lag with "lockTSE"; save but record value as stale
434 if ( $lockTSE >= 0 ) {
435 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
436 $wrapExtra[self
::FLD_FLAGS
] = self
::FLG_STALE
; // mark as stale
437 // Case B: any long-running transaction; ignore this set()
438 } elseif ( $age > self
::MAX_READ_LAG
) {
439 $this->logger
->warning( "Rejected set() for $key due to snapshot lag." );
441 return true; // no-op the write for being unsafe
442 // Case C: high replication lag; lower TTL instead of ignoring all set()s
443 } elseif ( $lag === false ||
$lag > self
::MAX_READ_LAG
) {
444 $ttl = $ttl ?
min( $ttl, self
::TTL_LAGGED
) : self
::TTL_LAGGED
;
445 $this->logger
->warning( "Lowered set() TTL for $key due to replication lag." );
446 // Case D: medium length request with medium replication lag; ignore this set()
448 $this->logger
->warning( "Rejected set() for $key due to high read lag." );
450 return true; // no-op the write for being unsafe
454 // Wrap that value with time/TTL/version metadata
455 $wrapped = $this->wrap( $value, $ttl, $now ) +
$wrapExtra;
457 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
458 return ( is_string( $cWrapped ) )
459 ?
false // key is tombstoned; do nothing
463 return $this->cache
->merge( self
::VALUE_KEY_PREFIX
. $key, $func, $ttl +
$staleTTL, 1 );
467 * Purge a key from all datacenters
469 * This should only be called when the underlying data (being cached)
470 * changes in a significant way. This deletes the key and starts a hold-off
471 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
472 * This is done to avoid the following race condition:
473 * - a) Some DB data changes and delete() is called on a corresponding key
474 * - b) A request refills the key with a stale value from a lagged DB
475 * - c) The stale value is stuck there until the key is expired/evicted
477 * This is implemented by storing a special "tombstone" value at the cache
478 * key that this class recognizes; get() calls will return false for the key
479 * and any set() calls will refuse to replace tombstone values at the key.
480 * For this to always avoid stale value writes, the following must hold:
481 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
482 * - b) If lag is higher, the DB will have gone into read-only mode already
484 * Note that set() can also be lag-aware and lower the TTL if it's high.
486 * When using potentially long-running ACID transactions, a good pattern is
487 * to use a pre-commit hook to issue the delete. This means that immediately
488 * after commit, callers will see the tombstone in cache upon purge relay.
489 * It also avoids the following race condition:
490 * - a) T1 begins, changes a row, and calls delete()
491 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
492 * - c) T2 starts, reads the row and calls set() due to a cache miss
493 * - d) T1 finally commits
494 * - e) Stale value is stuck in cache
498 * $dbw->startAtomic( __METHOD__ ); // start of request
499 * ... <execute some stuff> ...
500 * // Update the row in the DB
501 * $dbw->update( ... );
502 * $key = $cache->makeKey( 'homes', $homeId );
503 * // Purge the corresponding cache entry just before committing
504 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
505 * $cache->delete( $key );
507 * ... <execute some stuff> ...
508 * $dbw->endAtomic( __METHOD__ ); // end of request
511 * The $ttl parameter can be used when purging values that have not actually changed
512 * recently. For example, a cleanup script to purge cache entries does not really need
513 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
514 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
516 * If called twice on the same key, then the last hold-off TTL takes precedence. For
517 * idempotence, the $ttl should not vary for different delete() calls on the same key.
519 * @param string $key Cache key
520 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
521 * @return bool True if the item was purged or not found, false on failure
523 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
524 $key = self
::VALUE_KEY_PREFIX
. $key;
527 // Publish the purge to all datacenters
528 $ok = $this->relayDelete( $key );
530 // Publish the purge to all datacenters
531 $ok = $this->relayPurge( $key, $ttl, self
::HOLDOFF_NONE
);
538 * Fetch the value of a timestamp "check" key
540 * The key will be *initialized* to the current time if not set,
541 * so only call this method if this behavior is actually desired
543 * The timestamp can be used to check whether a cached value is valid.
544 * Callers should not assume that this returns the same timestamp in
545 * all datacenters due to relay delays.
547 * The level of staleness can roughly be estimated from this key, but
548 * if the key was evicted from cache, such calculations may show the
549 * time since expiry as ~0 seconds.
551 * Note that "check" keys won't collide with other regular keys.
554 * @return float UNIX timestamp of the check key
556 final public function getCheckKeyTime( $key ) {
557 $key = self
::TIME_KEY_PREFIX
. $key;
559 $purge = self
::parsePurgeValue( $this->cache
->get( $key ) );
560 if ( $purge !== false ) {
561 $time = $purge[self
::FLD_TIME
];
563 // Casting assures identical floats for the next getCheckKeyTime() calls
564 $now = (string)microtime( true );
565 $this->cache
->add( $key,
566 $this->makePurgeValue( $now, self
::HOLDOFF_TTL
),
576 * Purge a "check" key from all datacenters, invalidating keys that use it
578 * This should only be called when the underlying data (being cached)
579 * changes in a significant way, and it is impractical to call delete()
580 * on all keys that should be changed. When get() is called on those
581 * keys, the relevant "check" keys must be supplied for this to work.
583 * The "check" key essentially represents a last-modified field.
584 * When touched, the field will be updated on all cache servers.
585 * Keys using it via get(), getMulti(), or getWithSetCallback() will
586 * be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
587 * by those methods to avoid race conditions where dependent keys get updated
588 * with stale values (e.g. from a DB replica DB).
590 * This is typically useful for keys with hardcoded names or in some cases
591 * dynamically generated names where a low number of combinations exist.
592 * When a few important keys get a large number of hits, a high cache
593 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
594 * method is less appropriate in such cases since the "time since expiry"
595 * cannot be inferred, causing any get() after the reset to treat the key
596 * as being "hot", resulting in more stale value usage.
598 * Note that "check" keys won't collide with other regular keys.
600 * @see WANObjectCache::get()
601 * @see WANObjectCache::getWithSetCallback()
602 * @see WANObjectCache::resetCheckKey()
604 * @param string $key Cache key
605 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
606 * @return bool True if the item was purged or not found, false on failure
608 final public function touchCheckKey( $key, $holdoff = self
::HOLDOFF_TTL
) {
609 // Publish the purge to all datacenters
610 return $this->relayPurge( self
::TIME_KEY_PREFIX
. $key, self
::CHECK_KEY_TTL
, $holdoff );
614 * Delete a "check" key from all datacenters, invalidating keys that use it
616 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
617 * or getWithSetCallback() will be invalidated. The differences are:
618 * - a) The "check" key will be deleted from all caches and lazily
619 * re-initialized when accessed (rather than set everywhere)
620 * - b) Thus, dependent keys will be known to be invalid, but not
621 * for how long (they are treated as "just" purged), which
622 * effects any lockTSE logic in getWithSetCallback()
623 * - c) Since "check" keys are initialized only on the server the key hashes
624 * to, any temporary ejection of that server will cause the value to be
625 * seen as purged as a new server will initialize the "check" key.
627 * The advantage is that this does not place high TTL keys on every cache
628 * server, making it better for code that will cache many different keys
629 * and either does not use lockTSE or uses a low enough TTL anyway.
631 * This is typically useful for keys with dynamically generated names
632 * where a high number of combinations exist.
634 * Note that "check" keys won't collide with other regular keys.
636 * @see WANObjectCache::get()
637 * @see WANObjectCache::getWithSetCallback()
638 * @see WANObjectCache::touchCheckKey()
640 * @param string $key Cache key
641 * @return bool True if the item was purged or not found, false on failure
643 final public function resetCheckKey( $key ) {
644 // Publish the purge to all datacenters
645 return $this->relayDelete( self
::TIME_KEY_PREFIX
. $key );
649 * Method to fetch/regenerate cache keys
651 * On cache miss, the key will be set to the callback result via set()
652 * (unless the callback returns false) and that result will be returned.
653 * The arguments supplied to the callback are:
654 * - $oldValue : current cache value or false if not present
655 * - &$ttl : a reference to the TTL which can be altered
656 * - &$setOpts : a reference to options for set() which can be altered
657 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
659 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
660 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
661 * value, but it can be used to maintain "most recent X" values that come from time or
662 * sequence based source data, provided that the "as of" id/time is tracked. Note that
663 * preemptive regeneration and $checkKeys can result in a non-false current value.
665 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
666 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
667 * regeneration will automatically be triggered using the callback.
669 * The simplest way to avoid stampedes for hot keys is to use
670 * the 'lockTSE' option in $opts. If cache purges are needed, also:
671 * - a) Pass $key into $checkKeys
672 * - b) Use touchCheckKey( $key ) instead of delete( $key )
674 * Example usage (typical key):
676 * $catInfo = $cache->getWithSetCallback(
677 * // Key to store the cached value under
678 * $cache->makeKey( 'cat-attributes', $catId ),
679 * // Time-to-live (in seconds)
680 * $cache::TTL_MINUTE,
681 * // Function that derives the new key value
682 * function ( $oldValue, &$ttl, array &$setOpts ) {
683 * $dbr = wfGetDB( DB_REPLICA );
684 * // Account for any snapshot/replica DB lag
685 * $setOpts += Database::getCacheSetOptions( $dbr );
687 * return $dbr->selectRow( ... );
692 * Example usage (key that is expensive and hot):
694 * $catConfig = $cache->getWithSetCallback(
695 * // Key to store the cached value under
696 * $cache->makeKey( 'site-cat-config' ),
697 * // Time-to-live (in seconds)
699 * // Function that derives the new key value
700 * function ( $oldValue, &$ttl, array &$setOpts ) {
701 * $dbr = wfGetDB( DB_REPLICA );
702 * // Account for any snapshot/replica DB lag
703 * $setOpts += Database::getCacheSetOptions( $dbr );
705 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
708 * // Calling touchCheckKey() on this key invalidates the cache
709 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
710 * // Try to only let one datacenter thread manage cache updates at a time
712 * // Avoid querying cache servers multiple times in a web request
713 * 'pcTTL' => $cache::TTL_PROC_LONG
718 * Example usage (key with dynamic dependencies):
720 * $catState = $cache->getWithSetCallback(
721 * // Key to store the cached value under
722 * $cache->makeKey( 'cat-state', $cat->getId() ),
723 * // Time-to-live (seconds)
725 * // Function that derives the new key value
726 * function ( $oldValue, &$ttl, array &$setOpts ) {
727 * // Determine new value from the DB
728 * $dbr = wfGetDB( DB_REPLICA );
729 * // Account for any snapshot/replica DB lag
730 * $setOpts += Database::getCacheSetOptions( $dbr );
732 * return CatState::newFromResults( $dbr->select( ... ) );
735 * // The "check" keys that represent things the value depends on;
736 * // Calling touchCheckKey() on any of them invalidates the cache
738 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
739 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
740 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
746 * Example usage (hot key holding most recent 100 events):
748 * $lastCatActions = $cache->getWithSetCallback(
749 * // Key to store the cached value under
750 * $cache->makeKey( 'cat-last-actions', 100 ),
751 * // Time-to-live (in seconds)
753 * // Function that derives the new key value
754 * function ( $oldValue, &$ttl, array &$setOpts ) {
755 * $dbr = wfGetDB( DB_REPLICA );
756 * // Account for any snapshot/replica DB lag
757 * $setOpts += Database::getCacheSetOptions( $dbr );
759 * // Start off with the last cached list
760 * $list = $oldValue ?: [];
761 * // Fetch the last 100 relevant rows in descending order;
762 * // only fetch rows newer than $list[0] to reduce scanning
763 * $rows = iterator_to_array( $dbr->select( ... ) );
764 * // Merge them and get the new "last 100" rows
765 * return array_slice( array_merge( $new, $list ), 0, 100 );
768 * // Try to only let one datacenter thread manage cache updates at a time
770 * // Use a magic value when no cache value is ready rather than stampeding
771 * 'busyValue' => 'computing'
776 * @see WANObjectCache::get()
777 * @see WANObjectCache::set()
779 * @param string $key Cache key
780 * @param integer $ttl Seconds to live for key updates. Special values are:
781 * - WANObjectCache::TTL_INDEFINITE: Cache forever
782 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
783 * @param callable $callback Value generation function
784 * @param array $opts Options map:
785 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
786 * touchCheckKey() or resetCheckKey() is called on any of these keys.
788 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
789 * ago, then try to have a single thread handle cache regeneration at any given time.
790 * Other threads will try to use stale values if possible. If, on miss, the time since
791 * expiration is low, the assumption is that the key is hot and that a stampede is worth
792 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
793 * higher this is set, the higher the worst-case staleness can be.
794 * Use WANObjectCache::TSE_NONE to disable this logic.
795 * Default: WANObjectCache::TSE_NONE.
796 * - busyValue: If no value exists and another thread is currently regenerating it, use this
797 * as a fallback value (or a callback to generate such a value). This assures that cache
798 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
799 * against cache regeneration becoming very slow for some reason (greater than the TTL).
801 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
802 * network I/O when a key is read several times. This will not cache when the callback
803 * returns false, however. Note that any purges will not be seen while process cached;
804 * since the callback should use replica DBs and they may be lagged or have snapshot
805 * isolation anyway, this should not typically matter.
806 * Default: WANObjectCache::TTL_UNCACHEABLE.
807 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
808 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
809 * large values, small yet numerous values, or some values with a high cost of eviction.
810 * It is generally preferable to use a class constant when setting this value.
811 * This has no effect unless pcTTL is used.
812 * Default: WANObjectCache::PC_PRIMARY.
813 * - version: Integer version number. This allows for callers to make breaking changes to
814 * how values are stored while maintaining compatability and correct cache purges. New
815 * versions are stored alongside older versions concurrently. Avoid storing class objects
816 * however, as this reduces compatibility (due to serialization).
818 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
819 * This is useful if the source of a key is suspected of having possibly changed
820 * recently, and the caller wants any such changes to be reflected.
821 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
822 * - hotTTR: Expected time-till-refresh for keys that average ~1 hit/second.
823 * This should be greater than "ageNew". Keys with higher hit rates will regenerate
824 * more often. This is useful when a popular key is changed but the cache purge was
825 * delayed or lost. Seldom used keys are rarely affected by this setting, unless an
826 * extremely low "hotTTR" value is passed in.
827 * Default: WANObjectCache::HOT_TTR.
828 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
829 * than this. It becomes more likely over time, becoming certain once the key is expired.
830 * Default: WANObjectCache::LOW_TTL.
831 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
832 * Default: WANObjectCache::AGE_NEW.
833 * @return mixed Value found or written to the key
834 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
835 * @note Callable type hints are not used to avoid class-autoloading
837 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
838 $pcTTL = isset( $opts['pcTTL'] ) ?
$opts['pcTTL'] : self
::TTL_UNCACHEABLE
;
840 // Try the process cache if enabled
842 $group = isset( $opts['pcGroup'] ) ?
$opts['pcGroup'] : self
::PC_PRIMARY
;
843 $procCache = $this->getProcessCache( $group );
844 $value = $procCache->get( $key );
850 if ( $value === false ) {
851 // Fetch the value over the network
852 if ( isset( $opts['version'] ) ) {
853 $version = $opts['version'];
855 $cur = $this->doGetWithSetCallback(
858 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
859 use ( $callback, $version ) {
860 if ( is_array( $oldValue )
861 && array_key_exists( self
::VFLD_DATA
, $oldValue )
863 $oldData = $oldValue[self
::VFLD_DATA
];
865 // VFLD_DATA is not set if an old, unversioned, key is present
870 self
::VFLD_DATA
=> $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
871 self
::VFLD_VERSION
=> $version
877 if ( $cur[self
::VFLD_VERSION
] === $version ) {
878 // Value created or existed before with version; use it
879 $value = $cur[self
::VFLD_DATA
];
881 // Value existed before with a different version; use variant key.
882 // Reflect purges to $key by requiring that this key value be newer.
883 $value = $this->doGetWithSetCallback(
884 'cache-variant:' . md5( $key ) . ":$version",
887 // Regenerate value if not newer than $key
888 [ 'version' => null, 'minAsOf' => $asOf ] +
$opts
892 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
895 // Update the process cache if enabled
896 if ( $procCache && $value !== false ) {
897 $procCache->set( $key, $value, $pcTTL );
905 * Do the actual I/O for getWithSetCallback() when needed
907 * @see WANObjectCache::getWithSetCallback()
910 * @param integer $ttl
911 * @param callback $callback
912 * @param array $opts Options map for getWithSetCallback()
913 * @param float &$asOf Cache generation timestamp of returned value [returned]
915 * @note Callable type hints are not used to avoid class-autoloading
917 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
918 $lowTTL = isset( $opts['lowTTL'] ) ?
$opts['lowTTL'] : min( self
::LOW_TTL
, $ttl );
919 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
920 $checkKeys = isset( $opts['checkKeys'] ) ?
$opts['checkKeys'] : [];
921 $busyValue = isset( $opts['busyValue'] ) ?
$opts['busyValue'] : null;
922 $popWindow = isset( $opts['hotTTR'] ) ?
$opts['hotTTR'] : self
::HOT_TTR
;
923 $ageNew = isset( $opts['ageNew'] ) ?
$opts['ageNew'] : self
::AGE_NEW
;
924 $minTime = isset( $opts['minAsOf'] ) ?
$opts['minAsOf'] : self
::MIN_TIMESTAMP_NONE
;
925 $versioned = isset( $opts['version'] );
927 // Get the current key value
929 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
930 $value = $cValue; // return value
932 // Determine if a regeneration is desired
933 if ( $value !== false
935 && $this->isValid( $value, $versioned, $asOf, $minTime )
936 && !$this->worthRefreshExpiring( $curTTL, $lowTTL )
937 && !$this->worthRefreshPopular( $asOf, $ageNew, $popWindow )
942 // A deleted key with a negative TTL left must be tombstoned
943 $isTombstone = ( $curTTL !== null && $value === false );
944 // Assume a key is hot if requested soon after invalidation
945 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
946 // Use the mutex if there is no value and a busy fallback is given
947 $checkBusy = ( $busyValue !== null && $value === false );
948 // Decide whether a single thread should handle regenerations.
949 // This avoids stampedes when $checkKeys are bumped and when preemptive
950 // renegerations take too long. It also reduces regenerations while $key
951 // is tombstoned. This balances cache freshness with avoiding DB load.
952 $useMutex = ( $isHot ||
( $isTombstone && $lockTSE > 0 ) ||
$checkBusy );
954 $lockAcquired = false;
956 // Acquire a datacenter-local non-blocking lock
957 if ( $this->cache
->add( self
::MUTEX_KEY_PREFIX
. $key, 1, self
::LOCK_TTL
) ) {
958 // Lock acquired; this thread should update the key
959 $lockAcquired = true;
960 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
961 // If it cannot be acquired; then the stale value can be used
964 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
965 // For hot keys, either another thread has the lock or the lock failed;
966 // use the INTERIM value from the last thread that regenerated it.
967 $wrapped = $this->cache
->get( self
::INTERIM_KEY_PREFIX
. $key );
968 list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
969 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
970 $asOf = $wrapped[self
::FLD_TIME
];
974 // Use the busy fallback value if nothing else
975 if ( $busyValue !== null ) {
976 return is_callable( $busyValue ) ?
$busyValue() : $busyValue;
981 if ( !is_callable( $callback ) ) {
982 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
985 // Generate the new value from the callback...
987 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
988 // When delete() is called, writes are write-holed by the tombstone,
989 // so use a special INTERIM key to pass the new value around threads.
990 if ( ( $isTombstone && $lockTSE > 0 ) && $value !== false && $ttl >= 0 ) {
991 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
992 $newAsOf = microtime( true );
993 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
994 // Avoid using set() to avoid pointless mcrouter broadcasting
996 self
::INTERIM_KEY_PREFIX
. $key,
997 function () use ( $wrapped ) {
1005 if ( $value !== false && $ttl >= 0 ) {
1006 // Update the cache; this will fail if the key is tombstoned
1007 $setOpts['lockTSE'] = $lockTSE;
1008 $this->set( $key, $value, $ttl, $setOpts );
1011 if ( $lockAcquired ) {
1012 // Avoid using delete() to avoid pointless mcrouter broadcasting
1013 $this->cache
->changeTTL( self
::MUTEX_KEY_PREFIX
. $key, 1 );
1020 * @see BagOStuff::makeKey()
1021 * @param string ... Key component
1025 public function makeKey() {
1026 return call_user_func_array( [ $this->cache
, __FUNCTION__
], func_get_args() );
1030 * @see BagOStuff::makeGlobalKey()
1031 * @param string ... Key component
1035 public function makeGlobalKey() {
1036 return call_user_func_array( [ $this->cache
, __FUNCTION__
], func_get_args() );
1040 * Get the "last error" registered; clearLastError() should be called manually
1041 * @return int ERR_* class constant for the "last error" registry
1043 final public function getLastError() {
1044 if ( $this->lastRelayError
) {
1045 // If the cache and the relayer failed, focus on the latter.
1046 // An update not making it to the relayer means it won't show up
1047 // in other DCs (nor will consistent re-hashing see up-to-date values).
1048 // On the other hand, if just the cache update failed, then it should
1049 // eventually be applied by the relayer.
1050 return $this->lastRelayError
;
1053 $code = $this->cache
->getLastError();
1055 case BagOStuff
::ERR_NONE
:
1056 return self
::ERR_NONE
;
1057 case BagOStuff
::ERR_NO_RESPONSE
:
1058 return self
::ERR_NO_RESPONSE
;
1059 case BagOStuff
::ERR_UNREACHABLE
:
1060 return self
::ERR_UNREACHABLE
;
1062 return self
::ERR_UNEXPECTED
;
1067 * Clear the "last error" registry
1069 final public function clearLastError() {
1070 $this->cache
->clearLastError();
1071 $this->lastRelayError
= self
::ERR_NONE
;
1075 * Clear the in-process caches; useful for testing
1079 public function clearProcessCache() {
1080 $this->processCaches
= [];
1084 * @param integer $flag ATTR_* class constant
1085 * @return integer QOS_* class constant
1088 public function getQoS( $flag ) {
1089 return $this->cache
->getQoS( $flag );
1093 * Get a TTL that is higher for objects that have not changed recently
1095 * This is useful for keys that get explicit purges and DB or purge relay
1096 * lag is a potential concern (especially how it interacts with CDN cache)
1100 * // Last-modified time of page
1101 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1102 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1103 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1104 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1105 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1108 * @param integer|float $mtime UNIX timestamp
1109 * @param integer $maxTTL Maximum TTL (seconds)
1110 * @param integer $minTTL Minimum TTL (seconds); Default: 30
1111 * @param float $factor Value in the range (0,1); Default: .2
1112 * @return integer Adaptive TTL
1115 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = .2 ) {
1116 if ( is_float( $mtime ) ||
ctype_digit( $mtime ) ) {
1117 $mtime = (int)$mtime; // handle fractional seconds and string integers
1120 if ( !is_int( $mtime ) ||
$mtime <= 0 ) {
1121 return $minTTL; // no last-modified time provided
1124 $age = time() - $mtime;
1126 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1130 * Do the actual async bus purge of a key
1132 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1134 * @param string $key Cache key
1135 * @param integer $ttl How long to keep the tombstone [seconds]
1136 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1137 * @return bool Success
1139 protected function relayPurge( $key, $ttl, $holdoff ) {
1140 if ( $this->purgeRelayer
instanceof EventRelayerNull
) {
1141 // This handles the mcrouter and the single-DC case
1142 $ok = $this->cache
->set( $key,
1143 $this->makePurgeValue( microtime( true ), self
::HOLDOFF_NONE
),
1147 $event = $this->cache
->modifySimpleRelayEvent( [
1150 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1151 'ttl' => max( $ttl, 1 ),
1152 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1155 $ok = $this->purgeRelayer
->notify( $this->purgeChannel
, $event );
1157 $this->lastRelayError
= self
::ERR_RELAY
;
1165 * Do the actual async bus delete of a key
1167 * @param string $key Cache key
1168 * @return bool Success
1170 protected function relayDelete( $key ) {
1171 if ( $this->purgeRelayer
instanceof EventRelayerNull
) {
1172 // This handles the mcrouter and the single-DC case
1173 $ok = $this->cache
->delete( $key );
1175 $event = $this->cache
->modifySimpleRelayEvent( [
1180 $ok = $this->purgeRelayer
->notify( $this->purgeChannel
, $event );
1182 $this->lastRelayError
= self
::ERR_RELAY
;
1190 * Check if a key should be regenerated (using random probability)
1192 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
1193 * of returning true increases steadily from 0% to 100% as the $curTTL
1194 * moves from $lowTTL to 0 seconds. This handles widely varying
1195 * levels of cache access traffic.
1197 * @param float $curTTL Approximate TTL left on the key if present
1198 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1201 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1202 if ( $curTTL >= $lowTTL ) {
1204 } elseif ( $curTTL <= 0 ) {
1208 $chance = ( 1 - $curTTL / $lowTTL );
1210 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
1214 * Check if a key is due for randomized regeneration due to its popularity
1216 * This is used so that popular keys can preemptively refresh themselves for higher
1217 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
1218 * in cache with their high nominal TTL. This means popular keys keep good consistency,
1219 * whether the data changes frequently or not, and long-tail keys get to stay in cache
1220 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
1222 * @param float $asOf UNIX timestamp of the value
1223 * @param integer $ageNew Age of key when this might recommend refreshing (seconds)
1224 * @param integer $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
1227 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh ) {
1228 $age = microtime( true ) - $asOf;
1229 $timeOld = $age - $ageNew;
1230 if ( $timeOld <= 0 ) {
1234 // Lifecycle is: new, ramp-up refresh chance, full refresh chance
1235 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self
::RAMPUP_TTL
/ 2, 1 );
1236 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1237 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1238 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1239 $chance = 1 / ( self
::HIT_RATE_HIGH
* $refreshWindowSec );
1241 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1242 $chance *= ( $timeOld <= self
::RAMPUP_TTL
) ?
$timeOld / self
::RAMPUP_TTL
: 1;
1244 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
1248 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1250 * @param array $value
1251 * @param bool $versioned
1252 * @param float $asOf The time $value was generated
1253 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1256 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1257 if ( $versioned && !isset( $value[self
::VFLD_VERSION
] ) ) {
1259 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1267 * Do not use this method outside WANObjectCache
1269 * @param mixed $value
1270 * @param integer $ttl [0=forever]
1271 * @param float $now Unix Current timestamp just before calling set()
1274 protected function wrap( $value, $ttl, $now ) {
1276 self
::FLD_VERSION
=> self
::VERSION
,
1277 self
::FLD_VALUE
=> $value,
1278 self
::FLD_TTL
=> $ttl,
1279 self
::FLD_TIME
=> $now
1284 * Do not use this method outside WANObjectCache
1286 * @param array|string|bool $wrapped
1287 * @param float $now Unix Current timestamp (preferrably pre-query)
1288 * @return array (mixed; false if absent/invalid, current time left)
1290 protected function unwrap( $wrapped, $now ) {
1291 // Check if the value is a tombstone
1292 $purge = self
::parsePurgeValue( $wrapped );
1293 if ( $purge !== false ) {
1294 // Purged values should always have a negative current $ttl
1295 $curTTL = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
1296 return [ false, $curTTL ];
1299 if ( !is_array( $wrapped ) // not found
1300 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
1301 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
1303 return [ false, null ];
1306 $flags = isset( $wrapped[self
::FLD_FLAGS
] ) ?
$wrapped[self
::FLD_FLAGS
] : 0;
1307 if ( ( $flags & self
::FLG_STALE
) == self
::FLG_STALE
) {
1308 // Treat as expired, with the cache time as the expiration
1309 $age = $now - $wrapped[self
::FLD_TIME
];
1310 $curTTL = min( -$age, self
::TINY_NEGATIVE
);
1311 } elseif ( $wrapped[self
::FLD_TTL
] > 0 ) {
1312 // Get the approximate time left on the key
1313 $age = $now - $wrapped[self
::FLD_TIME
];
1314 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
1316 // Key had no TTL, so the time left is unbounded
1320 return [ $wrapped[self
::FLD_VALUE
], $curTTL ];
1324 * @param array $keys
1325 * @param string $prefix
1328 protected static function prefixCacheKeys( array $keys, $prefix ) {
1330 foreach ( $keys as $key ) {
1331 $res[] = $prefix . $key;
1338 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1339 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1340 * or false if value isn't a valid purge value
1342 protected static function parsePurgeValue( $value ) {
1343 if ( !is_string( $value ) ) {
1346 $segments = explode( ':', $value, 3 );
1347 if ( !isset( $segments[0] ) ||
!isset( $segments[1] )
1348 ||
"{$segments[0]}:" !== self
::PURGE_VAL_PREFIX
1352 if ( !isset( $segments[2] ) ) {
1353 // Back-compat with old purge values without holdoff
1354 $segments[2] = self
::HOLDOFF_TTL
;
1357 self
::FLD_TIME
=> (float)$segments[1],
1358 self
::FLD_HOLDOFF
=> (int)$segments[2],
1363 * @param float $timestamp
1364 * @param int $holdoff In seconds
1365 * @return string Wrapped purge value
1367 protected function makePurgeValue( $timestamp, $holdoff ) {
1368 return self
::PURGE_VAL_PREFIX
. (float)$timestamp . ':' . (int)$holdoff;
1372 * @param string $group
1373 * @return HashBagOStuff
1375 protected function getProcessCache( $group ) {
1376 if ( !isset( $this->processCaches
[$group] ) ) {
1377 list( , $n ) = explode( ':', $group );
1378 $this->processCaches
[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
1381 return $this->processCaches
[$group];