objectcache: fix a few documentation mistakes
[lhc/web/wiklou.git] / includes / libs / objectcache / WANObjectCache.php
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @ingroup Cache
20 */
21
22 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26
27 /**
28 * Multi-datacenter aware caching interface
29 *
30 * All operations go to the local datacenter cache, except for delete(),
31 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
32 *
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
44 *
45 * The simplest purge method is delete().
46 *
47 * There are three supported ways to handle broadcasted operations:
48 * - a) Configure the 'purge' EventRelayer to point to a valid PubSub endpoint
49 * that has subscribed listeners on the cache servers applying the cache updates.
50 * - b) 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).
56 * - c) Ignore the 'purge' EventRelayer configuration (default is NullEventRelayer)
57 * and set up dynomite as cache middleware between the web servers and either
58 * memcached or redis. This will also broadcast all key setting operations, not just purges,
59 * which can be useful for cache warming. Writes are eventually consistent via the
60 * Dynamo replication model (see https://github.com/Netflix/dynomite).
61 *
62 * Broadcasted operations like delete() and touchCheckKey() are done asynchronously
63 * in all datacenters this way, though the local one should likely be near immediate.
64 *
65 * This means that callers in all datacenters may see older values for however many
66 * milliseconds that the purge took to reach that datacenter. As with any cache, this
67 * should not be relied on for cases where reads are used to determine writes to source
68 * (e.g. non-cache) data stores, except when reading immutable data.
69 *
70 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
71 * to avoid collisions with keys that are not wrapped as metadata arrays. The
72 * prefixes are as follows:
73 * - a) "WANCache:v" : used for regular value keys
74 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
75 * - c) "WANCache:t" : used for storing timestamp "check" keys
76 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
77 *
78 * @ingroup Cache
79 * @since 1.26
80 */
81 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
82 /** @var BagOStuff The local datacenter cache */
83 protected $cache;
84 /** @var HashBagOStuff[] Map of group PHP instance caches */
85 protected $processCaches = [];
86 /** @var string Purge channel name */
87 protected $purgeChannel;
88 /** @var EventRelayer Bus that handles purge broadcasts */
89 protected $purgeRelayer;
90 /** @var LoggerInterface */
91 protected $logger;
92 /** @var StatsdDataFactoryInterface */
93 protected $stats;
94 /** @var bool Whether to use "interim" caching while keys are tombstoned */
95 protected $useInterimHoldOffCaching = true;
96
97 /** @var int ERR_* constant for the "last error" registry */
98 protected $lastRelayError = self::ERR_NONE;
99
100 /** @var int Callback stack depth for getWithSetCallback() */
101 private $callbackDepth = 0;
102 /** @var mixed[] Temporary warm-up cache */
103 private $warmupCache = [];
104 /** @var int Key fetched */
105 private $warmupKeyMisses = 0;
106
107 /** Max time expected to pass between delete() and DB commit finishing */
108 const MAX_COMMIT_DELAY = 3;
109 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
110 const MAX_READ_LAG = 7;
111 /** Seconds to tombstone keys on delete() */
112 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
113
114 /** Seconds to keep dependency purge keys around */
115 const CHECK_KEY_TTL = self::TTL_YEAR;
116 /** Seconds to keep interim value keys for tombstoned keys around */
117 const INTERIM_KEY_TTL = 1;
118
119 /** Seconds to keep lock keys around */
120 const LOCK_TTL = 10;
121 /** Default remaining TTL at which to consider pre-emptive regeneration */
122 const LOW_TTL = 30;
123 /** Default time-since-expiry on a miss that makes a key "hot" */
124 const LOCK_TSE = 1;
125
126 /** Never consider performing "popularity" refreshes until a key reaches this age */
127 const AGE_NEW = 60;
128 /** The time length of the "popularity" refresh window for hot keys */
129 const HOT_TTR = 900;
130 /** Hits/second for a refresh to be expected within the "popularity" window */
131 const HIT_RATE_HIGH = 1;
132 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
133 const RAMPUP_TTL = 30;
134
135 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
136 const TTL_UNCACHEABLE = -1;
137 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
138 const TSE_NONE = -1;
139 /** Max TTL to store keys when a data sourced is lagged */
140 const TTL_LAGGED = 30;
141 /** Idiom for delete() for "no hold-off" */
142 const HOLDOFF_NONE = 0;
143 /** Idiom for set()/getWithSetCallback() for "do not augment the storage medium TTL" */
144 const STALE_TTL_NONE = 0;
145 /** Idiom for set()/getWithSetCallback() for "no post-expired grace period" */
146 const GRACE_TTL_NONE = 0;
147
148 /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
149 const MIN_TIMESTAMP_NONE = 0.0;
150
151 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
152 const TINY_NEGATIVE = -0.000001;
153
154 /** Cache format version number */
155 const VERSION = 1;
156
157 const FLD_VERSION = 0; // key to cache version number
158 const FLD_VALUE = 1; // key to the cached value
159 const FLD_TTL = 2; // key to the original TTL
160 const FLD_TIME = 3; // key to the cache time
161 const FLD_FLAGS = 4; // key to the flags bitfield
162 const FLD_HOLDOFF = 5; // key to any hold-off TTL
163
164 /** @var int Treat this value as expired-on-arrival */
165 const FLG_STALE = 1;
166
167 const ERR_NONE = 0; // no error
168 const ERR_NO_RESPONSE = 1; // no response
169 const ERR_UNREACHABLE = 2; // can't connect
170 const ERR_UNEXPECTED = 3; // response gave some error
171 const ERR_RELAY = 4; // relay broadcast failed
172
173 const VALUE_KEY_PREFIX = 'WANCache:v:';
174 const INTERIM_KEY_PREFIX = 'WANCache:i:';
175 const TIME_KEY_PREFIX = 'WANCache:t:';
176 const MUTEX_KEY_PREFIX = 'WANCache:m:';
177
178 const PURGE_VAL_PREFIX = 'PURGED:';
179
180 const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
181 const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
182
183 const PC_PRIMARY = 'primary:1000'; // process cache name and max key count
184
185 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
186
187 /**
188 * @param array $params
189 * - cache : BagOStuff object for a persistent cache
190 * - channels : Map of (action => channel string). Actions include "purge".
191 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
192 * - logger : LoggerInterface object
193 * - stats : LoggerInterface object
194 */
195 public function __construct( array $params ) {
196 $this->cache = $params['cache'];
197 $this->purgeChannel = isset( $params['channels']['purge'] )
198 ? $params['channels']['purge']
199 : self::DEFAULT_PURGE_CHANNEL;
200 $this->purgeRelayer = isset( $params['relayers']['purge'] )
201 ? $params['relayers']['purge']
202 : new EventRelayerNull( [] );
203 $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
204 $this->stats = isset( $params['stats'] ) ? $params['stats'] : new NullStatsdDataFactory();
205 }
206
207 public function setLogger( LoggerInterface $logger ) {
208 $this->logger = $logger;
209 }
210
211 /**
212 * Get an instance that wraps EmptyBagOStuff
213 *
214 * @return WANObjectCache
215 */
216 public static function newEmpty() {
217 return new static( [
218 'cache' => new EmptyBagOStuff(),
219 'pool' => 'empty'
220 ] );
221 }
222
223 /**
224 * Fetch the value of a key from cache
225 *
226 * If supplied, $curTTL is set to the remaining TTL (current time left):
227 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
228 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
229 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
230 * - d) null; if $key does not exist and is not tombstoned
231 *
232 * If a key is tombstoned, $curTTL will reflect the time since delete().
233 *
234 * The timestamp of $key will be checked against the last-purge timestamp
235 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
236 * initialized to the current timestamp. If any of $checkKeys have a timestamp
237 * greater than that of $key, then $curTTL will reflect how long ago $key
238 * became invalid. Callers can use $curTTL to know when the value is stale.
239 * The $checkKeys parameter allow mass invalidations by updating a single key:
240 * - a) Each "check" key represents "last purged" of some source data
241 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
242 * - c) When the source data that "check" keys represent changes,
243 * the touchCheckKey() method is called on them
244 *
245 * Source data entities might exists in a DB that uses snapshot isolation
246 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
247 * isolation can largely be maintained by doing the following:
248 * - a) Calling delete() on entity change *and* creation, before DB commit
249 * - b) Keeping transaction duration shorter than delete() hold-off TTL
250 *
251 * However, pre-snapshot values might still be seen if an update was made
252 * in a remote datacenter but the purge from delete() didn't relay yet.
253 *
254 * Consider using getWithSetCallback() instead of get() and set() cycles.
255 * That method has cache slam avoiding features for hot/expensive keys.
256 *
257 * @param string $key Cache key made from makeKey() or makeGlobalKey()
258 * @param mixed &$curTTL Approximate TTL left on the key if present/tombstoned [returned]
259 * @param array $checkKeys List of "check" keys
260 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
261 * @return mixed Value of cache key or false on failure
262 */
263 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
264 $curTTLs = [];
265 $asOfs = [];
266 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
267 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
268 $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null;
269
270 return isset( $values[$key] ) ? $values[$key] : false;
271 }
272
273 /**
274 * Fetch the value of several keys from cache
275 *
276 * @see WANObjectCache::get()
277 *
278 * @param array $keys List of cache keys made from makeKey() or makeGlobalKey()
279 * @param array &$curTTLs Map of (key => approximate TTL left) for existing keys [returned]
280 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
281 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
282 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
283 * @return array Map of (key => value) for keys that exist and are not tombstoned
284 */
285 final public function getMulti(
286 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
287 ) {
288 $result = [];
289 $curTTLs = [];
290 $asOfs = [];
291
292 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
293 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
294
295 $checkKeysForAll = [];
296 $checkKeysByKey = [];
297 $checkKeysFlat = [];
298 foreach ( $checkKeys as $i => $checkKeyGroup ) {
299 $prefixed = self::prefixCacheKeys( (array)$checkKeyGroup, self::TIME_KEY_PREFIX );
300 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
301 // Is this check keys for a specific cache key, or for all keys being fetched?
302 if ( is_int( $i ) ) {
303 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
304 } else {
305 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
306 ? array_merge( $checkKeysByKey[$i], $prefixed )
307 : $prefixed;
308 }
309 }
310
311 // Fetch all of the raw values
312 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
313 if ( $this->warmupCache ) {
314 $wrappedValues = array_intersect_key( $this->warmupCache, array_flip( $keysGet ) );
315 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) ); // keys left to fetch
316 $this->warmupKeyMisses += count( $keysGet );
317 } else {
318 $wrappedValues = [];
319 }
320 if ( $keysGet ) {
321 $wrappedValues += $this->cache->getMulti( $keysGet );
322 }
323 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
324 $now = $this->getCurrentTime();
325
326 // Collect timestamps from all "check" keys
327 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
328 $purgeValuesByKey = [];
329 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
330 $purgeValuesByKey[$cacheKey] =
331 $this->processCheckKeys( $checks, $wrappedValues, $now );
332 }
333
334 // Get the main cache value for each key and validate them
335 foreach ( $valueKeys as $vKey ) {
336 if ( !isset( $wrappedValues[$vKey] ) ) {
337 continue; // not found
338 }
339
340 $key = substr( $vKey, $vPrefixLen ); // unprefix
341
342 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
343 if ( $value !== false ) {
344 $result[$key] = $value;
345
346 // Force dependant keys to be invalid for a while after purging
347 // to reduce race conditions involving stale data getting cached
348 $purgeValues = $purgeValuesForAll;
349 if ( isset( $purgeValuesByKey[$key] ) ) {
350 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
351 }
352 foreach ( $purgeValues as $purge ) {
353 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
354 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
355 // How long ago this value was expired by *this* check key
356 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
357 // How long ago this value was expired by *any* known check key
358 $curTTL = min( $curTTL, $ago );
359 }
360 }
361 }
362 $curTTLs[$key] = $curTTL;
363 $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
364 }
365
366 return $result;
367 }
368
369 /**
370 * @since 1.27
371 * @param array $timeKeys List of prefixed time check keys
372 * @param array $wrappedValues
373 * @param float $now
374 * @return array List of purge value arrays
375 */
376 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
377 $purgeValues = [];
378 foreach ( $timeKeys as $timeKey ) {
379 $purge = isset( $wrappedValues[$timeKey] )
380 ? self::parsePurgeValue( $wrappedValues[$timeKey] )
381 : false;
382 if ( $purge === false ) {
383 // Key is not set or invalid; regenerate
384 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
385 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
386 $purge = self::parsePurgeValue( $newVal );
387 }
388 $purgeValues[] = $purge;
389 }
390 return $purgeValues;
391 }
392
393 /**
394 * Set the value of a key in cache
395 *
396 * Simply calling this method when source data changes is not valid because
397 * the changes do not replicate to the other WAN sites. In that case, delete()
398 * should be used instead. This method is intended for use on cache misses.
399 *
400 * If the data was read from a snapshot-isolated transactions (e.g. the default
401 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
402 * - a) T1 starts
403 * - b) T2 updates a row, calls delete(), and commits
404 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
405 * - d) T1 reads the row and calls set() due to a cache miss
406 * - e) Stale value is stuck in cache
407 *
408 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
409 *
410 * Example usage:
411 * @code
412 * $dbr = wfGetDB( DB_REPLICA );
413 * $setOpts = Database::getCacheSetOptions( $dbr );
414 * // Fetch the row from the DB
415 * $row = $dbr->selectRow( ... );
416 * $key = $cache->makeKey( 'building', $buildingId );
417 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
418 * @endcode
419 *
420 * @param string $key Cache key
421 * @param mixed $value
422 * @param int $ttl Seconds to live. Special values are:
423 * - WANObjectCache::TTL_INDEFINITE: Cache forever
424 * @param array $opts Options map:
425 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
426 * before the data was read or, if applicable, the replica DB lag before
427 * the snapshot-isolated transaction the data was read from started.
428 * Use false to indicate that replication is not running.
429 * Default: 0 seconds
430 * - since : UNIX timestamp of the data in $value. Typically, this is either
431 * the current time the data was read or (if applicable) the time when
432 * the snapshot-isolated transaction the data was read from started.
433 * Default: 0 seconds
434 * - pending : Whether this data is possibly from an uncommitted write transaction.
435 * Generally, other threads should not see values from the future and
436 * they certainly should not see ones that ended up getting rolled back.
437 * Default: false
438 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
439 * with this TTL and flag it as stale. This is only useful if the reads for this key
440 * use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set
441 * then it will still add on to this TTL in the excessive lag scenario.
442 * Default: WANObjectCache::TSE_NONE
443 * - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
444 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
445 * will call the regeneration callback in such cases, passing in the old value
446 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
447 * on the old value's as-of time when it is verified as still being correct.
448 * Default: WANObjectCache::STALE_TTL_NONE.
449 * @note Options added in 1.28: staleTTL
450 * @return bool Success
451 */
452 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
453 $now = $this->getCurrentTime();
454 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
455 $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : self::STALE_TTL_NONE;
456 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
457 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
458
459 // Do not cache potentially uncommitted data as it might get rolled back
460 if ( !empty( $opts['pending'] ) ) {
461 $this->logger->info( 'Rejected set() for {cachekey} due to pending writes.',
462 [ 'cachekey' => $key ] );
463
464 return true; // no-op the write for being unsafe
465 }
466
467 $wrapExtra = []; // additional wrapped value fields
468 // Check if there's a risk of writing stale data after the purge tombstone expired
469 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
470 // Case A: read lag with "lockTSE"; save but record value as stale
471 if ( $lockTSE >= 0 ) {
472 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
473 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
474 // Case B: any long-running transaction; ignore this set()
475 } elseif ( $age > self::MAX_READ_LAG ) {
476 $this->logger->info( 'Rejected set() for {cachekey} due to snapshot lag.',
477 [ 'cachekey' => $key ] );
478
479 return true; // no-op the write for being unsafe
480 // Case C: high replication lag; lower TTL instead of ignoring all set()s
481 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
482 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
483 $this->logger->warning( 'Lowered set() TTL for {cachekey} due to replication lag.',
484 [ 'cachekey' => $key ] );
485 // Case D: medium length request with medium replication lag; ignore this set()
486 } else {
487 $this->logger->info( 'Rejected set() for {cachekey} due to high read lag.',
488 [ 'cachekey' => $key ] );
489
490 return true; // no-op the write for being unsafe
491 }
492 }
493
494 // Wrap that value with time/TTL/version metadata
495 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
496
497 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
498 return ( is_string( $cWrapped ) )
499 ? false // key is tombstoned; do nothing
500 : $wrapped;
501 };
502
503 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl + $staleTTL, 1 );
504 }
505
506 /**
507 * Purge a key from all datacenters
508 *
509 * This should only be called when the underlying data (being cached)
510 * changes in a significant way. This deletes the key and starts a hold-off
511 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
512 * This is done to avoid the following race condition:
513 * - a) Some DB data changes and delete() is called on a corresponding key
514 * - b) A request refills the key with a stale value from a lagged DB
515 * - c) The stale value is stuck there until the key is expired/evicted
516 *
517 * This is implemented by storing a special "tombstone" value at the cache
518 * key that this class recognizes; get() calls will return false for the key
519 * and any set() calls will refuse to replace tombstone values at the key.
520 * For this to always avoid stale value writes, the following must hold:
521 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
522 * - b) If lag is higher, the DB will have gone into read-only mode already
523 *
524 * Note that set() can also be lag-aware and lower the TTL if it's high.
525 *
526 * When using potentially long-running ACID transactions, a good pattern is
527 * to use a pre-commit hook to issue the delete. This means that immediately
528 * after commit, callers will see the tombstone in cache upon purge relay.
529 * It also avoids the following race condition:
530 * - a) T1 begins, changes a row, and calls delete()
531 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
532 * - c) T2 starts, reads the row and calls set() due to a cache miss
533 * - d) T1 finally commits
534 * - e) Stale value is stuck in cache
535 *
536 * Example usage:
537 * @code
538 * $dbw->startAtomic( __METHOD__ ); // start of request
539 * ... <execute some stuff> ...
540 * // Update the row in the DB
541 * $dbw->update( ... );
542 * $key = $cache->makeKey( 'homes', $homeId );
543 * // Purge the corresponding cache entry just before committing
544 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
545 * $cache->delete( $key );
546 * } );
547 * ... <execute some stuff> ...
548 * $dbw->endAtomic( __METHOD__ ); // end of request
549 * @endcode
550 *
551 * The $ttl parameter can be used when purging values that have not actually changed
552 * recently. For example, a cleanup script to purge cache entries does not really need
553 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
554 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
555 *
556 * If called twice on the same key, then the last hold-off TTL takes precedence. For
557 * idempotence, the $ttl should not vary for different delete() calls on the same key.
558 *
559 * @param string $key Cache key
560 * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
561 * @return bool True if the item was purged or not found, false on failure
562 */
563 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
564 $key = self::VALUE_KEY_PREFIX . $key;
565
566 if ( $ttl <= 0 ) {
567 // Publish the purge to all datacenters
568 $ok = $this->relayDelete( $key );
569 } else {
570 // Publish the purge to all datacenters
571 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE );
572 }
573
574 return $ok;
575 }
576
577 /**
578 * Fetch the value of a timestamp "check" key
579 *
580 * The key will be *initialized* to the current time if not set,
581 * so only call this method if this behavior is actually desired
582 *
583 * The timestamp can be used to check whether a cached value is valid.
584 * Callers should not assume that this returns the same timestamp in
585 * all datacenters due to relay delays.
586 *
587 * The level of staleness can roughly be estimated from this key, but
588 * if the key was evicted from cache, such calculations may show the
589 * time since expiry as ~0 seconds.
590 *
591 * Note that "check" keys won't collide with other regular keys.
592 *
593 * @param string $key
594 * @return float UNIX timestamp of the check key
595 */
596 final public function getCheckKeyTime( $key ) {
597 $key = self::TIME_KEY_PREFIX . $key;
598
599 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
600 if ( $purge !== false ) {
601 $time = $purge[self::FLD_TIME];
602 } else {
603 // Casting assures identical floats for the next getCheckKeyTime() calls
604 $now = (string)$this->getCurrentTime();
605 $this->cache->add( $key,
606 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
607 self::CHECK_KEY_TTL
608 );
609 $time = (float)$now;
610 }
611
612 return $time;
613 }
614
615 /**
616 * Purge a "check" key from all datacenters, invalidating keys that use it
617 *
618 * This should only be called when the underlying data (being cached)
619 * changes in a significant way, and it is impractical to call delete()
620 * on all keys that should be changed. When get() is called on those
621 * keys, the relevant "check" keys must be supplied for this to work.
622 *
623 * The "check" key essentially represents a last-modified time of an entity.
624 * When the key is touched, the timestamp will be updated to the current time.
625 * Keys using the "check" key via get(), getMulti(), or getWithSetCallback() will
626 * be invalidated. This approach is useful if many keys depend on a single entity.
627 *
628 * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the
629 * future by get*() methods in order to avoid race conditions where keys are updated
630 * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check"
631 * key, making it possible to know the timestamp of the last change to the corresponding
632 * entities in most cases. This might use more cache space than resetCheckKey().
633 *
634 * When a few important keys get a large number of hits, a high cache time is usually
635 * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate
636 * in such cases since the "time since expiry" cannot be inferred, causing any get()
637 * after the reset to treat the key as being "hot", resulting in more stale value usage.
638 *
639 * Note that "check" keys won't collide with other regular keys.
640 *
641 * @see WANObjectCache::get()
642 * @see WANObjectCache::getWithSetCallback()
643 * @see WANObjectCache::resetCheckKey()
644 *
645 * @param string $key Cache key
646 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
647 * @return bool True if the item was purged or not found, false on failure
648 */
649 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
650 // Publish the purge to all datacenters
651 return $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
652 }
653
654 /**
655 * Delete a "check" key from all datacenters, invalidating keys that use it
656 *
657 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
658 * or getWithSetCallback() will be invalidated. The differences are:
659 * - a) The "check" key will be deleted from all caches and lazily
660 * re-initialized when accessed (rather than set everywhere)
661 * - b) Thus, dependent keys will be known to be invalid, but not
662 * for how long (they are treated as "just" purged), which
663 * effects any lockTSE logic in getWithSetCallback()
664 * - c) Since "check" keys are initialized only on the server the key hashes
665 * to, any temporary ejection of that server will cause the value to be
666 * seen as purged as a new server will initialize the "check" key.
667 *
668 * The advantage here is that the "check" keys, which have high TTLs, will only
669 * be created when a get*() method actually uses that key. This is better when
670 * a large number of "check" keys are invalided in a short period of time.
671 *
672 * Note that "check" keys won't collide with other regular keys.
673 *
674 * @see WANObjectCache::get()
675 * @see WANObjectCache::getWithSetCallback()
676 * @see WANObjectCache::touchCheckKey()
677 *
678 * @param string $key Cache key
679 * @return bool True if the item was purged or not found, false on failure
680 */
681 final public function resetCheckKey( $key ) {
682 // Publish the purge to all datacenters
683 return $this->relayDelete( self::TIME_KEY_PREFIX . $key );
684 }
685
686 /**
687 * Method to fetch/regenerate cache keys
688 *
689 * On cache miss, the key will be set to the callback result via set()
690 * (unless the callback returns false) and that result will be returned.
691 * The arguments supplied to the callback are:
692 * - $oldValue : current cache value or false if not present
693 * - &$ttl : a reference to the TTL which can be altered
694 * - &$setOpts : a reference to options for set() which can be altered
695 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
696 *
697 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
698 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
699 * value, but it can be used to maintain "most recent X" values that come from time or
700 * sequence based source data, provided that the "as of" id/time is tracked. Note that
701 * preemptive regeneration and $checkKeys can result in a non-false current value.
702 *
703 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
704 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
705 * regeneration will automatically be triggered using the callback.
706 *
707 * The $ttl argument and "hotTTR" option (in $opts) use time-dependant randomization
708 * to avoid stampedes. Keys that are slow to regenerate and either heavily used
709 * or subject to explicit (unpredictable) purges, may need additional mechanisms.
710 * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts).
711 * If explicit purges are needed, also:
712 * - a) Pass $key into $checkKeys
713 * - b) Use touchCheckKey( $key ) instead of delete( $key )
714 *
715 * Example usage (typical key):
716 * @code
717 * $catInfo = $cache->getWithSetCallback(
718 * // Key to store the cached value under
719 * $cache->makeKey( 'cat-attributes', $catId ),
720 * // Time-to-live (in seconds)
721 * $cache::TTL_MINUTE,
722 * // Function that derives the new key value
723 * function ( $oldValue, &$ttl, array &$setOpts ) {
724 * $dbr = wfGetDB( DB_REPLICA );
725 * // Account for any snapshot/replica DB lag
726 * $setOpts += Database::getCacheSetOptions( $dbr );
727 *
728 * return $dbr->selectRow( ... );
729 * }
730 * );
731 * @endcode
732 *
733 * Example usage (key that is expensive and hot):
734 * @code
735 * $catConfig = $cache->getWithSetCallback(
736 * // Key to store the cached value under
737 * $cache->makeKey( 'site-cat-config' ),
738 * // Time-to-live (in seconds)
739 * $cache::TTL_DAY,
740 * // Function that derives the new key value
741 * function ( $oldValue, &$ttl, array &$setOpts ) {
742 * $dbr = wfGetDB( DB_REPLICA );
743 * // Account for any snapshot/replica DB lag
744 * $setOpts += Database::getCacheSetOptions( $dbr );
745 *
746 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
747 * },
748 * [
749 * // Calling touchCheckKey() on this key invalidates the cache
750 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
751 * // Try to only let one datacenter thread manage cache updates at a time
752 * 'lockTSE' => 30,
753 * // Avoid querying cache servers multiple times in a web request
754 * 'pcTTL' => $cache::TTL_PROC_LONG
755 * ]
756 * );
757 * @endcode
758 *
759 * Example usage (key with dynamic dependencies):
760 * @code
761 * $catState = $cache->getWithSetCallback(
762 * // Key to store the cached value under
763 * $cache->makeKey( 'cat-state', $cat->getId() ),
764 * // Time-to-live (seconds)
765 * $cache::TTL_HOUR,
766 * // Function that derives the new key value
767 * function ( $oldValue, &$ttl, array &$setOpts ) {
768 * // Determine new value from the DB
769 * $dbr = wfGetDB( DB_REPLICA );
770 * // Account for any snapshot/replica DB lag
771 * $setOpts += Database::getCacheSetOptions( $dbr );
772 *
773 * return CatState::newFromResults( $dbr->select( ... ) );
774 * },
775 * [
776 * // The "check" keys that represent things the value depends on;
777 * // Calling touchCheckKey() on any of them invalidates the cache
778 * 'checkKeys' => [
779 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
780 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
781 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
782 * ]
783 * ]
784 * );
785 * @endcode
786 *
787 * Example usage (hot key holding most recent 100 events):
788 * @code
789 * $lastCatActions = $cache->getWithSetCallback(
790 * // Key to store the cached value under
791 * $cache->makeKey( 'cat-last-actions', 100 ),
792 * // Time-to-live (in seconds)
793 * 10,
794 * // Function that derives the new key value
795 * function ( $oldValue, &$ttl, array &$setOpts ) {
796 * $dbr = wfGetDB( DB_REPLICA );
797 * // Account for any snapshot/replica DB lag
798 * $setOpts += Database::getCacheSetOptions( $dbr );
799 *
800 * // Start off with the last cached list
801 * $list = $oldValue ?: [];
802 * // Fetch the last 100 relevant rows in descending order;
803 * // only fetch rows newer than $list[0] to reduce scanning
804 * $rows = iterator_to_array( $dbr->select( ... ) );
805 * // Merge them and get the new "last 100" rows
806 * return array_slice( array_merge( $new, $list ), 0, 100 );
807 * },
808 * [
809 * // Try to only let one datacenter thread manage cache updates at a time
810 * 'lockTSE' => 30,
811 * // Use a magic value when no cache value is ready rather than stampeding
812 * 'busyValue' => 'computing'
813 * ]
814 * );
815 * @endcode
816 *
817 * @see WANObjectCache::get()
818 * @see WANObjectCache::set()
819 *
820 * @param string $key Cache key made from makeKey() or makeGlobalKey()
821 * @param int $ttl Seconds to live for key updates. Special values are:
822 * - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
823 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
824 * @param callable $callback Value generation function
825 * @param array $opts Options map:
826 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
827 * touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This
828 * is useful if thousands or millions of keys depend on the same entity. The entity can
829 * simply have its "check" key updated whenever the entity is modified.
830 * Default: [].
831 * - graceTTL: Consider reusing expired values instead of refreshing them if they expired
832 * less than this many seconds ago. The odds of a refresh becomes more likely over time,
833 * becoming certain once the grace period is reached. This can reduce traffic spikes
834 * when millions of keys are compared to the same "check" key and touchCheckKey()
835 * or resetCheckKey() is called on that "check" key.
836 * Default: WANObjectCache::GRACE_TTL_NONE.
837 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
838 * ago, then try to have a single thread handle cache regeneration at any given time.
839 * Other threads will try to use stale values if possible. If, on miss, the time since
840 * expiration is low, the assumption is that the key is hot and that a stampede is worth
841 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
842 * higher this is set, the higher the worst-case staleness can be.
843 * Use WANObjectCache::TSE_NONE to disable this logic.
844 * Default: WANObjectCache::TSE_NONE.
845 * - busyValue: If no value exists and another thread is currently regenerating it, use this
846 * as a fallback value (or a callback to generate such a value). This assures that cache
847 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
848 * against cache regeneration becoming very slow for some reason (greater than the TTL).
849 * Default: null.
850 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
851 * network I/O when a key is read several times. This will not cache when the callback
852 * returns false, however. Note that any purges will not be seen while process cached;
853 * since the callback should use replica DBs and they may be lagged or have snapshot
854 * isolation anyway, this should not typically matter.
855 * Default: WANObjectCache::TTL_UNCACHEABLE.
856 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
857 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
858 * large values, small yet numerous values, or some values with a high cost of eviction.
859 * It is generally preferable to use a class constant when setting this value.
860 * This has no effect unless pcTTL is used.
861 * Default: WANObjectCache::PC_PRIMARY.
862 * - version: Integer version number. This allows for callers to make breaking changes to
863 * how values are stored while maintaining compatability and correct cache purges. New
864 * versions are stored alongside older versions concurrently. Avoid storing class objects
865 * however, as this reduces compatibility (due to serialization).
866 * Default: null.
867 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
868 * This is useful if the source of a key is suspected of having possibly changed
869 * recently, and the caller wants any such changes to be reflected.
870 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
871 * - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per
872 * second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this
873 * TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old.
874 * This uses randomization to avoid triggering cache stampedes. The TTR is useful at
875 * reducing the impact of missed cache purges, since the effect of a heavily referenced
876 * key being stale is worse than that of a rarely referenced key. Unlike simply lowering
877 * $ttl, seldomly used keys are largely unaffected by this option, which makes it
878 * possible to have a high hit rate for the "long-tail" of less-used keys.
879 * Default: WANObjectCache::HOT_TTR.
880 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
881 * than this. It becomes more likely over time, becoming certain once the key is expired.
882 * This helps avoid cache stampedes that might be triggered due to the key expiring.
883 * Default: WANObjectCache::LOW_TTL.
884 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
885 * Default: WANObjectCache::AGE_NEW.
886 * - staleTTL: Seconds to keep the key around if it is stale. This means that on cache
887 * miss the callback may get $oldValue/$oldAsOf values for keys that have already been
888 * expired for this specified time. This is useful if adaptiveTTL() is used on the old
889 * value's as-of time when it is verified as still being correct.
890 * Default: WANObjectCache::STALE_TTL_NONE
891 * @return mixed Value found or written to the key
892 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
893 * @note Options added in 1.31: staleTTL, graceTTL
894 * @note Callable type hints are not used to avoid class-autoloading
895 */
896 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
897 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
898
899 // Try the process cache if enabled and the cache callback is not within a cache callback.
900 // Process cache use in nested callbacks is not lag-safe with regard to HOLDOFF_TTL since
901 // the in-memory value is further lagged than the shared one since it uses a blind TTL.
902 if ( $pcTTL >= 0 && $this->callbackDepth == 0 ) {
903 $group = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY;
904 $procCache = $this->getProcessCache( $group );
905 $value = $procCache->get( $key );
906 } else {
907 $procCache = false;
908 $value = false;
909 }
910
911 if ( $value === false ) {
912 // Fetch the value over the network
913 if ( isset( $opts['version'] ) ) {
914 $version = $opts['version'];
915 $asOf = null;
916 $cur = $this->doGetWithSetCallback(
917 $key,
918 $ttl,
919 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
920 use ( $callback, $version ) {
921 if ( is_array( $oldValue )
922 && array_key_exists( self::VFLD_DATA, $oldValue )
923 && array_key_exists( self::VFLD_VERSION, $oldValue )
924 && $oldValue[self::VFLD_VERSION] === $version
925 ) {
926 $oldData = $oldValue[self::VFLD_DATA];
927 } else {
928 // VFLD_DATA is not set if an old, unversioned, key is present
929 $oldData = false;
930 $oldAsOf = null;
931 }
932
933 return [
934 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
935 self::VFLD_VERSION => $version
936 ];
937 },
938 $opts,
939 $asOf
940 );
941 if ( $cur[self::VFLD_VERSION] === $version ) {
942 // Value created or existed before with version; use it
943 $value = $cur[self::VFLD_DATA];
944 } else {
945 // Value existed before with a different version; use variant key.
946 // Reflect purges to $key by requiring that this key value be newer.
947 $value = $this->doGetWithSetCallback(
948 $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), $version ),
949 $ttl,
950 $callback,
951 // Regenerate value if not newer than $key
952 [ 'version' => null, 'minAsOf' => $asOf ] + $opts
953 );
954 }
955 } else {
956 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
957 }
958
959 // Update the process cache if enabled
960 if ( $procCache && $value !== false ) {
961 $procCache->set( $key, $value, $pcTTL );
962 }
963 }
964
965 return $value;
966 }
967
968 /**
969 * Do the actual I/O for getWithSetCallback() when needed
970 *
971 * @see WANObjectCache::getWithSetCallback()
972 *
973 * @param string $key
974 * @param int $ttl
975 * @param callback $callback
976 * @param array $opts Options map for getWithSetCallback()
977 * @param float &$asOf Cache generation timestamp of returned value [returned]
978 * @return mixed
979 * @note Callable type hints are not used to avoid class-autoloading
980 */
981 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
982 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
983 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
984 $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : self::STALE_TTL_NONE;
985 $graceTTL = isset( $opts['graceTTL'] ) ? $opts['graceTTL'] : self::GRACE_TTL_NONE;
986 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
987 $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
988 $popWindow = isset( $opts['hotTTR'] ) ? $opts['hotTTR'] : self::HOT_TTR;
989 $ageNew = isset( $opts['ageNew'] ) ? $opts['ageNew'] : self::AGE_NEW;
990 $minTime = isset( $opts['minAsOf'] ) ? $opts['minAsOf'] : self::MIN_TIMESTAMP_NONE;
991 $versioned = isset( $opts['version'] );
992
993 // Get a collection name to describe this class of key
994 $kClass = $this->determineKeyClass( $key );
995
996 // Get the current key value
997 $curTTL = null;
998 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
999 $value = $cValue; // return value
1000
1001 $preCallbackTime = $this->getCurrentTime();
1002 // Determine if a cached value regeneration is needed or desired
1003 if ( $value !== false
1004 && $this->isAliveOrInGracePeriod( $curTTL, $graceTTL )
1005 && $this->isValid( $value, $versioned, $asOf, $minTime )
1006 && !$this->worthRefreshExpiring( $curTTL, $lowTTL )
1007 && !$this->worthRefreshPopular( $asOf, $ageNew, $popWindow, $preCallbackTime )
1008 ) {
1009 $this->stats->increment( "wanobjectcache.$kClass.hit.good" );
1010
1011 return $value;
1012 }
1013
1014 // A deleted key with a negative TTL left must be tombstoned
1015 $isTombstone = ( $curTTL !== null && $value === false );
1016 if ( $isTombstone && $lockTSE <= 0 ) {
1017 // Use the INTERIM value for tombstoned keys to reduce regeneration load
1018 $lockTSE = self::INTERIM_KEY_TTL;
1019 }
1020 // Assume a key is hot if requested soon after invalidation
1021 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
1022 // Use the mutex if there is no value and a busy fallback is given
1023 $checkBusy = ( $busyValue !== null && $value === false );
1024 // Decide whether a single thread should handle regenerations.
1025 // This avoids stampedes when $checkKeys are bumped and when preemptive
1026 // renegerations take too long. It also reduces regenerations while $key
1027 // is tombstoned. This balances cache freshness with avoiding DB load.
1028 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
1029
1030 $lockAcquired = false;
1031 if ( $useMutex ) {
1032 // Acquire a datacenter-local non-blocking lock
1033 if ( $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
1034 // Lock acquired; this thread should update the key
1035 $lockAcquired = true;
1036 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1037 $this->stats->increment( "wanobjectcache.$kClass.hit.stale" );
1038 // If it cannot be acquired; then the stale value can be used
1039 return $value;
1040 } else {
1041 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
1042 // For hot keys, either another thread has the lock or the lock failed;
1043 // use the INTERIM value from the last thread that regenerated it.
1044 $value = $this->getInterimValue( $key, $versioned, $minTime, $asOf );
1045 if ( $value !== false ) {
1046 $this->stats->increment( "wanobjectcache.$kClass.hit.volatile" );
1047
1048 return $value;
1049 }
1050 // Use the busy fallback value if nothing else
1051 if ( $busyValue !== null ) {
1052 $this->stats->increment( "wanobjectcache.$kClass.miss.busy" );
1053
1054 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
1055 }
1056 }
1057 }
1058
1059 if ( !is_callable( $callback ) ) {
1060 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
1061 }
1062
1063 // Generate the new value from the callback...
1064 $setOpts = [];
1065 ++$this->callbackDepth;
1066 try {
1067 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
1068 } finally {
1069 --$this->callbackDepth;
1070 }
1071 $valueIsCacheable = ( $value !== false && $ttl >= 0 );
1072
1073 // When delete() is called, writes are write-holed by the tombstone,
1074 // so use a special INTERIM key to pass the new value around threads.
1075 if ( ( $isTombstone && $lockTSE > 0 ) && $valueIsCacheable ) {
1076 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
1077 $newAsOf = $this->getCurrentTime();
1078 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
1079 // Avoid using set() to avoid pointless mcrouter broadcasting
1080 $this->setInterimValue( $key, $wrapped, $tempTTL );
1081 }
1082
1083 if ( $valueIsCacheable ) {
1084 $setOpts['lockTSE'] = $lockTSE;
1085 $setOpts['staleTTL'] = $staleTTL;
1086 // Use best known "since" timestamp if not provided
1087 $setOpts += [ 'since' => $preCallbackTime ];
1088 // Update the cache; this will fail if the key is tombstoned
1089 $this->set( $key, $value, $ttl, $setOpts );
1090 }
1091
1092 if ( $lockAcquired ) {
1093 // Avoid using delete() to avoid pointless mcrouter broadcasting
1094 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, (int)$preCallbackTime - 60 );
1095 }
1096
1097 $this->stats->increment( "wanobjectcache.$kClass.miss.compute" );
1098
1099 return $value;
1100 }
1101
1102 /**
1103 * @param string $key
1104 * @param bool $versioned
1105 * @param float $minTime
1106 * @param mixed $asOf
1107 * @return mixed
1108 */
1109 protected function getInterimValue( $key, $versioned, $minTime, &$asOf ) {
1110 if ( !$this->useInterimHoldOffCaching ) {
1111 return false; // disabled
1112 }
1113
1114 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
1115 list( $value ) = $this->unwrap( $wrapped, $this->getCurrentTime() );
1116 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1117 $asOf = $wrapped[self::FLD_TIME];
1118
1119 return $value;
1120 }
1121
1122 return false;
1123 }
1124
1125 /**
1126 * @param string $key
1127 * @param array $wrapped
1128 * @param int $tempTTL
1129 */
1130 protected function setInterimValue( $key, $wrapped, $tempTTL ) {
1131 $this->cache->merge(
1132 self::INTERIM_KEY_PREFIX . $key,
1133 function () use ( $wrapped ) {
1134 return $wrapped;
1135 },
1136 $tempTTL,
1137 1
1138 );
1139 }
1140
1141 /**
1142 * Method to fetch multiple cache keys at once with regeneration
1143 *
1144 * This works the same as getWithSetCallback() except:
1145 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1146 * - b) The $callback argument expects a callback taking the following arguments:
1147 * - $id: ID of an entity to query
1148 * - $oldValue : the prior cache value or false if none was present
1149 * - &$ttl : a reference to the new value TTL in seconds
1150 * - &$setOpts : a reference to options for set() which can be altered
1151 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present
1152 * Aside from the additional $id argument, the other arguments function the same
1153 * way they do in getWithSetCallback().
1154 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1155 *
1156 * @see WANObjectCache::getWithSetCallback()
1157 * @see WANObjectCache::getMultiWithUnionSetCallback()
1158 *
1159 * Example usage:
1160 * @code
1161 * $rows = $cache->getMultiWithSetCallback(
1162 * // Map of cache keys to entity IDs
1163 * $cache->makeMultiKeys(
1164 * $this->fileVersionIds(),
1165 * function ( $id, WANObjectCache $cache ) {
1166 * return $cache->makeKey( 'file-version', $id );
1167 * }
1168 * ),
1169 * // Time-to-live (in seconds)
1170 * $cache::TTL_DAY,
1171 * // Function that derives the new key value
1172 * function ( $id, $oldValue, &$ttl, array &$setOpts ) {
1173 * $dbr = wfGetDB( DB_REPLICA );
1174 * // Account for any snapshot/replica DB lag
1175 * $setOpts += Database::getCacheSetOptions( $dbr );
1176 *
1177 * // Load the row for this file
1178 * $queryInfo = File::getQueryInfo();
1179 * $row = $dbr->selectRow(
1180 * $queryInfo['tables'],
1181 * $queryInfo['fields'],
1182 * [ 'id' => $id ],
1183 * __METHOD__,
1184 * [],
1185 * $queryInfo['joins']
1186 * );
1187 *
1188 * return $row ? (array)$row : false;
1189 * },
1190 * [
1191 * // Process cache for 30 seconds
1192 * 'pcTTL' => 30,
1193 * // Use a dedicated 500 item cache (initialized on-the-fly)
1194 * 'pcGroup' => 'file-versions:500'
1195 * ]
1196 * );
1197 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1198 * @endcode
1199 *
1200 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1201 * @param int $ttl Seconds to live for key updates
1202 * @param callable $callback Callback the yields entity regeneration callbacks
1203 * @param array $opts Options map
1204 * @return array Map of (cache key => value) in the same order as $keyedIds
1205 * @since 1.28
1206 */
1207 final public function getMultiWithSetCallback(
1208 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1209 ) {
1210 $valueKeys = array_keys( $keyedIds->getArrayCopy() );
1211 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
1212
1213 // Load required keys into process cache in one go
1214 $this->warmupCache = $this->getRawKeysForWarmup(
1215 $this->getNonProcessCachedKeys( $valueKeys, $opts ),
1216 $checkKeys
1217 );
1218 $this->warmupKeyMisses = 0;
1219
1220 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1221 $id = null; // current entity ID
1222 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf ) use ( $callback, &$id ) {
1223 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1224 };
1225
1226 $values = [];
1227 foreach ( $keyedIds as $key => $id ) { // preserve order
1228 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1229 }
1230
1231 $this->warmupCache = [];
1232
1233 return $values;
1234 }
1235
1236 /**
1237 * Method to fetch/regenerate multiple cache keys at once
1238 *
1239 * This works the same as getWithSetCallback() except:
1240 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1241 * - b) The $callback argument expects a callback returning a map of (ID => new value)
1242 * for all entity IDs in $regenById and it takes the following arguments:
1243 * - $ids: a list of entity IDs to regenerate
1244 * - &$ttls: a reference to the (entity ID => new TTL) map
1245 * - &$setOpts: a reference to options for set() which can be altered
1246 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1247 * - d) The "lockTSE" and "busyValue" options are ignored
1248 *
1249 * @see WANObjectCache::getWithSetCallback()
1250 * @see WANObjectCache::getMultiWithSetCallback()
1251 *
1252 * Example usage:
1253 * @code
1254 * $rows = $cache->getMultiWithUnionSetCallback(
1255 * // Map of cache keys to entity IDs
1256 * $cache->makeMultiKeys(
1257 * $this->fileVersionIds(),
1258 * function ( $id, WANObjectCache $cache ) {
1259 * return $cache->makeKey( 'file-version', $id );
1260 * }
1261 * ),
1262 * // Time-to-live (in seconds)
1263 * $cache::TTL_DAY,
1264 * // Function that derives the new key value
1265 * function ( array $ids, array &$ttls, array &$setOpts ) {
1266 * $dbr = wfGetDB( DB_REPLICA );
1267 * // Account for any snapshot/replica DB lag
1268 * $setOpts += Database::getCacheSetOptions( $dbr );
1269 *
1270 * // Load the rows for these files
1271 * $rows = [];
1272 * $queryInfo = File::getQueryInfo();
1273 * $res = $dbr->select(
1274 * $queryInfo['tables'],
1275 * $queryInfo['fields'],
1276 * [ 'id' => $ids ],
1277 * __METHOD__,
1278 * [],
1279 * $queryInfo['joins']
1280 * );
1281 * foreach ( $res as $row ) {
1282 * $rows[$row->id] = $row;
1283 * $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
1284 * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
1285 * }
1286 *
1287 * return $rows;
1288 * },
1289 * ]
1290 * );
1291 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1292 * @endcode
1293 *
1294 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1295 * @param int $ttl Seconds to live for key updates
1296 * @param callable $callback Callback the yields entity regeneration callbacks
1297 * @param array $opts Options map
1298 * @return array Map of (cache key => value) in the same order as $keyedIds
1299 * @since 1.30
1300 */
1301 final public function getMultiWithUnionSetCallback(
1302 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1303 ) {
1304 $idsByValueKey = $keyedIds->getArrayCopy();
1305 $valueKeys = array_keys( $idsByValueKey );
1306 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
1307 unset( $opts['lockTSE'] ); // incompatible
1308 unset( $opts['busyValue'] ); // incompatible
1309
1310 // Load required keys into process cache in one go
1311 $keysGet = $this->getNonProcessCachedKeys( $valueKeys, $opts );
1312 $this->warmupCache = $this->getRawKeysForWarmup( $keysGet, $checkKeys );
1313 $this->warmupKeyMisses = 0;
1314
1315 // IDs of entities known to be in need of regeneration
1316 $idsRegen = [];
1317
1318 // Find out which keys are missing/deleted/stale
1319 $curTTLs = [];
1320 $asOfs = [];
1321 $curByKey = $this->getMulti( $keysGet, $curTTLs, $checkKeys, $asOfs );
1322 foreach ( $keysGet as $key ) {
1323 if ( !array_key_exists( $key, $curByKey ) || $curTTLs[$key] < 0 ) {
1324 $idsRegen[] = $idsByValueKey[$key];
1325 }
1326 }
1327
1328 // Run the callback to populate the regeneration value map for all required IDs
1329 $newSetOpts = [];
1330 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
1331 $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
1332
1333 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1334 $id = null; // current entity ID
1335 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1336 use ( $callback, &$id, $newValsById, $newTTLsById, $newSetOpts )
1337 {
1338 if ( array_key_exists( $id, $newValsById ) ) {
1339 // Value was already regerated as expected, so use the value in $newValsById
1340 $newValue = $newValsById[$id];
1341 $ttl = $newTTLsById[$id];
1342 $setOpts = $newSetOpts;
1343 } else {
1344 // Pre-emptive/popularity refresh and version mismatch cases are not detected
1345 // above and thus $newValsById has no entry. Run $callback on this single entity.
1346 $ttls = [ $id => $ttl ];
1347 $newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
1348 $ttl = $ttls[$id];
1349 }
1350
1351 return $newValue;
1352 };
1353
1354 // Run the cache-aside logic using warmupCache instead of persistent cache queries
1355 $values = [];
1356 foreach ( $idsByValueKey as $key => $id ) { // preserve order
1357 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1358 }
1359
1360 $this->warmupCache = [];
1361
1362 return $values;
1363 }
1364
1365 /**
1366 * Locally set a key to expire soon if it is stale based on $purgeTimestamp
1367 *
1368 * This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids
1369 * broadcasting in mcrouter setups and also avoids races with new tombstones.
1370 *
1371 * @param string $key Cache key
1372 * @param int $purgeTimestamp UNIX timestamp of purge
1373 * @param bool &$isStale Whether the key is stale
1374 * @return bool Success
1375 * @since 1.28
1376 */
1377 public function reap( $key, $purgeTimestamp, &$isStale = false ) {
1378 $minAsOf = $purgeTimestamp + self::HOLDOFF_TTL;
1379 $wrapped = $this->cache->get( self::VALUE_KEY_PREFIX . $key );
1380 if ( is_array( $wrapped ) && $wrapped[self::FLD_TIME] < $minAsOf ) {
1381 $isStale = true;
1382 $this->logger->warning( "Reaping stale value key '$key'." );
1383 $ttlReap = self::HOLDOFF_TTL; // avoids races with tombstone creation
1384 $ok = $this->cache->changeTTL( self::VALUE_KEY_PREFIX . $key, $ttlReap );
1385 if ( !$ok ) {
1386 $this->logger->error( "Could not complete reap of key '$key'." );
1387 }
1388
1389 return $ok;
1390 }
1391
1392 $isStale = false;
1393
1394 return true;
1395 }
1396
1397 /**
1398 * Locally set a "check" key to expire soon if it is stale based on $purgeTimestamp
1399 *
1400 * @param string $key Cache key
1401 * @param int $purgeTimestamp UNIX timestamp of purge
1402 * @param bool &$isStale Whether the key is stale
1403 * @return bool Success
1404 * @since 1.28
1405 */
1406 public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
1407 $purge = $this->parsePurgeValue( $this->cache->get( self::TIME_KEY_PREFIX . $key ) );
1408 if ( $purge && $purge[self::FLD_TIME] < $purgeTimestamp ) {
1409 $isStale = true;
1410 $this->logger->warning( "Reaping stale check key '$key'." );
1411 $ok = $this->cache->changeTTL( self::TIME_KEY_PREFIX . $key, 1 );
1412 if ( !$ok ) {
1413 $this->logger->error( "Could not complete reap of check key '$key'." );
1414 }
1415
1416 return $ok;
1417 }
1418
1419 $isStale = false;
1420
1421 return false;
1422 }
1423
1424 /**
1425 * @see BagOStuff::makeKey()
1426 * @param string $class Key class
1427 * @param string $component [optional] Key component (starting with a key collection name)
1428 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1429 * @since 1.27
1430 */
1431 public function makeKey( $class, $component = null ) {
1432 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1433 }
1434
1435 /**
1436 * @see BagOStuff::makeGlobalKey()
1437 * @param string $class Key class
1438 * @param string $component [optional] Key component (starting with a key collection name)
1439 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1440 * @since 1.27
1441 */
1442 public function makeGlobalKey( $class, $component = null ) {
1443 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1444 }
1445
1446 /**
1447 * @param array $entities List of entity IDs
1448 * @param callable $keyFunc Callback yielding a key from (entity ID, this WANObjectCache)
1449 * @return ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
1450 * @since 1.28
1451 */
1452 public function makeMultiKeys( array $entities, callable $keyFunc ) {
1453 $map = [];
1454 foreach ( $entities as $entity ) {
1455 $map[$keyFunc( $entity, $this )] = $entity;
1456 }
1457
1458 return new ArrayIterator( $map );
1459 }
1460
1461 /**
1462 * Get the "last error" registered; clearLastError() should be called manually
1463 * @return int ERR_* class constant for the "last error" registry
1464 */
1465 final public function getLastError() {
1466 if ( $this->lastRelayError ) {
1467 // If the cache and the relayer failed, focus on the latter.
1468 // An update not making it to the relayer means it won't show up
1469 // in other DCs (nor will consistent re-hashing see up-to-date values).
1470 // On the other hand, if just the cache update failed, then it should
1471 // eventually be applied by the relayer.
1472 return $this->lastRelayError;
1473 }
1474
1475 $code = $this->cache->getLastError();
1476 switch ( $code ) {
1477 case BagOStuff::ERR_NONE:
1478 return self::ERR_NONE;
1479 case BagOStuff::ERR_NO_RESPONSE:
1480 return self::ERR_NO_RESPONSE;
1481 case BagOStuff::ERR_UNREACHABLE:
1482 return self::ERR_UNREACHABLE;
1483 default:
1484 return self::ERR_UNEXPECTED;
1485 }
1486 }
1487
1488 /**
1489 * Clear the "last error" registry
1490 */
1491 final public function clearLastError() {
1492 $this->cache->clearLastError();
1493 $this->lastRelayError = self::ERR_NONE;
1494 }
1495
1496 /**
1497 * Clear the in-process caches; useful for testing
1498 *
1499 * @since 1.27
1500 */
1501 public function clearProcessCache() {
1502 $this->processCaches = [];
1503 }
1504
1505 /**
1506 * Enable or disable the use of brief caching for tombstoned keys
1507 *
1508 * When a key is purged via delete(), there normally is a period where caching
1509 * is hold-off limited to an extremely short time. This method will disable that
1510 * caching, forcing the callback to run for any of:
1511 * - WANObjectCache::getWithSetCallback()
1512 * - WANObjectCache::getMultiWithSetCallback()
1513 * - WANObjectCache::getMultiWithUnionSetCallback()
1514 *
1515 * This is useful when both:
1516 * - a) the database used by the callback is known to be up-to-date enough
1517 * for some particular purpose (e.g. replica DB has applied transaction X)
1518 * - b) the caller needs to exploit that fact, and therefore needs to avoid the
1519 * use of inherently volatile and possibly stale interim keys
1520 *
1521 * @see WANObjectCache::delete()
1522 * @param bool $enabled Whether to enable interim caching
1523 * @since 1.31
1524 */
1525 public function useInterimHoldOffCaching( $enabled ) {
1526 $this->useInterimHoldOffCaching = $enabled;
1527 }
1528
1529 /**
1530 * @param int $flag ATTR_* class constant
1531 * @return int QOS_* class constant
1532 * @since 1.28
1533 */
1534 public function getQoS( $flag ) {
1535 return $this->cache->getQoS( $flag );
1536 }
1537
1538 /**
1539 * Get a TTL that is higher for objects that have not changed recently
1540 *
1541 * This is useful for keys that get explicit purges and DB or purge relay
1542 * lag is a potential concern (especially how it interacts with CDN cache)
1543 *
1544 * Example usage:
1545 * @code
1546 * // Last-modified time of page
1547 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1548 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1549 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1550 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1551 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1552 * @endcode
1553 *
1554 * Another use case is when there are no applicable "last modified" fields in the DB,
1555 * and there are too many dependencies for explicit purges to be viable, and the rate of
1556 * change to relevant content is unstable, and it is highly valued to have the cached value
1557 * be as up-to-date as possible.
1558 *
1559 * Example usage:
1560 * @code
1561 * $query = "<some complex query>";
1562 * $idListFromComplexQuery = $cache->getWithSetCallback(
1563 * $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
1564 * GraphQueryClass::STARTING_TTL,
1565 * function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
1566 * $gdb = $this->getReplicaGraphDbConnection();
1567 * // Account for any snapshot/replica DB lag
1568 * $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
1569 *
1570 * $newList = iterator_to_array( $gdb->query( $query ) );
1571 * sort( $newList, SORT_NUMERIC ); // normalize
1572 *
1573 * $minTTL = GraphQueryClass::MIN_TTL;
1574 * $maxTTL = GraphQueryClass::MAX_TTL;
1575 * if ( $oldValue !== false ) {
1576 * // Note that $oldAsOf is the last time this callback ran
1577 * $ttl = ( $newList === $oldValue )
1578 * // No change: cache for 150% of the age of $oldValue
1579 * ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
1580 * // Changed: cache for %50 of the age of $oldValue
1581 * : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
1582 * }
1583 *
1584 * return $newList;
1585 * },
1586 * [
1587 * // Keep stale values around for doing comparisons for TTL calculations.
1588 * // High values improve long-tail keys hit-rates, though might waste space.
1589 * 'staleTTL' => GraphQueryClass::GRACE_TTL
1590 * ]
1591 * );
1592 * @endcode
1593 *
1594 * @param int|float $mtime UNIX timestamp
1595 * @param int $maxTTL Maximum TTL (seconds)
1596 * @param int $minTTL Minimum TTL (seconds); Default: 30
1597 * @param float $factor Value in the range (0,1); Default: .2
1598 * @return int Adaptive TTL
1599 * @since 1.28
1600 */
1601 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
1602 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
1603 $mtime = (int)$mtime; // handle fractional seconds and string integers
1604 }
1605
1606 if ( !is_int( $mtime ) || $mtime <= 0 ) {
1607 return $minTTL; // no last-modified time provided
1608 }
1609
1610 $age = $this->getCurrentTime() - $mtime;
1611
1612 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1613 }
1614
1615 /**
1616 * @return int Number of warmup key cache misses last round
1617 * @since 1.30
1618 */
1619 public function getWarmupKeyMisses() {
1620 return $this->warmupKeyMisses;
1621 }
1622
1623 /**
1624 * Do the actual async bus purge of a key
1625 *
1626 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1627 *
1628 * @param string $key Cache key
1629 * @param int $ttl How long to keep the tombstone [seconds]
1630 * @param int $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1631 * @return bool Success
1632 */
1633 protected function relayPurge( $key, $ttl, $holdoff ) {
1634 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1635 // This handles the mcrouter and the single-DC case
1636 $ok = $this->cache->set( $key,
1637 $this->makePurgeValue( $this->getCurrentTime(), self::HOLDOFF_NONE ),
1638 $ttl
1639 );
1640 } else {
1641 $event = $this->cache->modifySimpleRelayEvent( [
1642 'cmd' => 'set',
1643 'key' => $key,
1644 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1645 'ttl' => max( $ttl, 1 ),
1646 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1647 ] );
1648
1649 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1650 if ( !$ok ) {
1651 $this->lastRelayError = self::ERR_RELAY;
1652 }
1653 }
1654
1655 return $ok;
1656 }
1657
1658 /**
1659 * Do the actual async bus delete of a key
1660 *
1661 * @param string $key Cache key
1662 * @return bool Success
1663 */
1664 protected function relayDelete( $key ) {
1665 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1666 // This handles the mcrouter and the single-DC case
1667 $ok = $this->cache->delete( $key );
1668 } else {
1669 $event = $this->cache->modifySimpleRelayEvent( [
1670 'cmd' => 'delete',
1671 'key' => $key,
1672 ] );
1673
1674 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1675 if ( !$ok ) {
1676 $this->lastRelayError = self::ERR_RELAY;
1677 }
1678 }
1679
1680 return $ok;
1681 }
1682
1683 /**
1684 * Check if a key is fresh or in the grace window and thus due for randomized reuse
1685 *
1686 * If $curTTL > 0 (e.g. not expired) this returns true. Otherwise, the chance of returning
1687 * true decrease steadily from 100% to 0% as the |$curTTL| moves from 0 to $graceTTL seconds.
1688 * This handles widely varying levels of cache access traffic.
1689 *
1690 * If $curTTL <= -$graceTTL (e.g. already expired), then this returns false.
1691 *
1692 * @param float $curTTL Approximate TTL left on the key if present
1693 * @param int $graceTTL Consider using stale values if $curTTL is greater than this
1694 * @return bool
1695 */
1696 protected function isAliveOrInGracePeriod( $curTTL, $graceTTL ) {
1697 if ( $curTTL > 0 ) {
1698 return true;
1699 } elseif ( $graceTTL <= 0 ) {
1700 return false;
1701 }
1702
1703 $ageStale = abs( $curTTL ); // seconds of staleness
1704 $curGTTL = ( $graceTTL - $ageStale ); // current grace-time-to-live
1705 if ( $curGTTL <= 0 ) {
1706 return false; // already out of grace period
1707 }
1708
1709 // Chance of using a stale value is the complement of the chance of refreshing it
1710 return !$this->worthRefreshExpiring( $curGTTL, $graceTTL );
1711 }
1712
1713 /**
1714 * Check if a key is nearing expiration and thus due for randomized regeneration
1715 *
1716 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance of returning true
1717 * increases steadily from 0% to 100% as the $curTTL moves from $lowTTL to 0 seconds.
1718 * This handles widely varying levels of cache access traffic.
1719 *
1720 * If $curTTL <= 0 (e.g. already expired), then this returns false.
1721 *
1722 * @param float $curTTL Approximate TTL left on the key if present
1723 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1724 * @return bool
1725 */
1726 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1727 if ( $lowTTL <= 0 ) {
1728 return false;
1729 } elseif ( $curTTL >= $lowTTL ) {
1730 return false;
1731 } elseif ( $curTTL <= 0 ) {
1732 return false;
1733 }
1734
1735 $chance = ( 1 - $curTTL / $lowTTL );
1736
1737 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1738 }
1739
1740 /**
1741 * Check if a key is due for randomized regeneration due to its popularity
1742 *
1743 * This is used so that popular keys can preemptively refresh themselves for higher
1744 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
1745 * in cache with their high nominal TTL. This means popular keys keep good consistency,
1746 * whether the data changes frequently or not, and long-tail keys get to stay in cache
1747 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
1748 *
1749 * @param float $asOf UNIX timestamp of the value
1750 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
1751 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
1752 * @param float $now The current UNIX timestamp
1753 * @return bool
1754 */
1755 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
1756 if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
1757 return false;
1758 }
1759
1760 $age = $now - $asOf;
1761 $timeOld = $age - $ageNew;
1762 if ( $timeOld <= 0 ) {
1763 return false;
1764 }
1765
1766 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
1767 // Note that the "expected # of refreshes" for the ramp-up time range is half of what it
1768 // would be if P(refresh) was at its full value during that time range.
1769 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
1770 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1771 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1772 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1773 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
1774
1775 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1776 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
1777
1778 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1779 }
1780
1781 /**
1782 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1783 *
1784 * @param array $value
1785 * @param bool $versioned
1786 * @param float $asOf The time $value was generated
1787 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1788 * @return bool
1789 */
1790 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1791 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1792 return false;
1793 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1794 return false;
1795 }
1796
1797 return true;
1798 }
1799
1800 /**
1801 * Do not use this method outside WANObjectCache
1802 *
1803 * @param mixed $value
1804 * @param int $ttl [0=forever]
1805 * @param float $now Unix Current timestamp just before calling set()
1806 * @return array
1807 */
1808 protected function wrap( $value, $ttl, $now ) {
1809 return [
1810 self::FLD_VERSION => self::VERSION,
1811 self::FLD_VALUE => $value,
1812 self::FLD_TTL => $ttl,
1813 self::FLD_TIME => $now
1814 ];
1815 }
1816
1817 /**
1818 * Do not use this method outside WANObjectCache
1819 *
1820 * @param array|string|bool $wrapped
1821 * @param float $now Unix Current timestamp (preferrably pre-query)
1822 * @return array (mixed; false if absent/tombstoned/invalid, current time left)
1823 */
1824 protected function unwrap( $wrapped, $now ) {
1825 // Check if the value is a tombstone
1826 $purge = self::parsePurgeValue( $wrapped );
1827 if ( $purge !== false ) {
1828 // Purged values should always have a negative current $ttl
1829 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1830 return [ false, $curTTL ];
1831 }
1832
1833 if ( !is_array( $wrapped ) // not found
1834 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1835 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1836 ) {
1837 return [ false, null ];
1838 }
1839
1840 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1841 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1842 // Treat as expired, with the cache time as the expiration
1843 $age = $now - $wrapped[self::FLD_TIME];
1844 $curTTL = min( -$age, self::TINY_NEGATIVE );
1845 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1846 // Get the approximate time left on the key
1847 $age = $now - $wrapped[self::FLD_TIME];
1848 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1849 } else {
1850 // Key had no TTL, so the time left is unbounded
1851 $curTTL = INF;
1852 }
1853
1854 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1855 }
1856
1857 /**
1858 * @param array $keys
1859 * @param string $prefix
1860 * @return string[]
1861 */
1862 protected static function prefixCacheKeys( array $keys, $prefix ) {
1863 $res = [];
1864 foreach ( $keys as $key ) {
1865 $res[] = $prefix . $key;
1866 }
1867
1868 return $res;
1869 }
1870
1871 /**
1872 * @param string $key String of the format <scope>:<class>[:<class or variable>]...
1873 * @return string
1874 */
1875 protected function determineKeyClass( $key ) {
1876 $parts = explode( ':', $key );
1877
1878 return isset( $parts[1] ) ? $parts[1] : $parts[0]; // sanity
1879 }
1880
1881 /**
1882 * @return float UNIX timestamp
1883 * @codeCoverageIgnore
1884 */
1885 protected function getCurrentTime() {
1886 return microtime( true );
1887 }
1888
1889 /**
1890 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1891 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1892 * or false if value isn't a valid purge value
1893 */
1894 protected static function parsePurgeValue( $value ) {
1895 if ( !is_string( $value ) ) {
1896 return false;
1897 }
1898 $segments = explode( ':', $value, 3 );
1899 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1900 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1901 ) {
1902 return false;
1903 }
1904 if ( !isset( $segments[2] ) ) {
1905 // Back-compat with old purge values without holdoff
1906 $segments[2] = self::HOLDOFF_TTL;
1907 }
1908 return [
1909 self::FLD_TIME => (float)$segments[1],
1910 self::FLD_HOLDOFF => (int)$segments[2],
1911 ];
1912 }
1913
1914 /**
1915 * @param float $timestamp
1916 * @param int $holdoff In seconds
1917 * @return string Wrapped purge value
1918 */
1919 protected function makePurgeValue( $timestamp, $holdoff ) {
1920 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1921 }
1922
1923 /**
1924 * @param string $group
1925 * @return HashBagOStuff
1926 */
1927 protected function getProcessCache( $group ) {
1928 if ( !isset( $this->processCaches[$group] ) ) {
1929 list( , $n ) = explode( ':', $group );
1930 $this->processCaches[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
1931 }
1932
1933 return $this->processCaches[$group];
1934 }
1935
1936 /**
1937 * @param array $keys
1938 * @param array $opts
1939 * @return array List of keys
1940 */
1941 private function getNonProcessCachedKeys( array $keys, array $opts ) {
1942 $keysFound = [];
1943 if ( isset( $opts['pcTTL'] ) && $opts['pcTTL'] > 0 && $this->callbackDepth == 0 ) {
1944 $pcGroup = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY;
1945 $procCache = $this->getProcessCache( $pcGroup );
1946 foreach ( $keys as $key ) {
1947 if ( $procCache->get( $key ) !== false ) {
1948 $keysFound[] = $key;
1949 }
1950 }
1951 }
1952
1953 return array_diff( $keys, $keysFound );
1954 }
1955
1956 /**
1957 * @param array $keys
1958 * @param array $checkKeys
1959 * @return array Map of (cache key => mixed)
1960 */
1961 private function getRawKeysForWarmup( array $keys, array $checkKeys ) {
1962 if ( !$keys ) {
1963 return [];
1964 }
1965
1966 $keysWarmUp = [];
1967 // Get all the value keys to fetch...
1968 foreach ( $keys as $key ) {
1969 $keysWarmUp[] = self::VALUE_KEY_PREFIX . $key;
1970 }
1971 // Get all the check keys to fetch...
1972 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
1973 if ( is_int( $i ) ) {
1974 // Single check key that applies to all value keys
1975 $keysWarmUp[] = self::TIME_KEY_PREFIX . $checkKeyOrKeys;
1976 } else {
1977 // List of check keys that apply to value key $i
1978 $keysWarmUp = array_merge(
1979 $keysWarmUp,
1980 self::prefixCacheKeys( $checkKeyOrKeys, self::TIME_KEY_PREFIX )
1981 );
1982 }
1983 }
1984
1985 $warmupCache = $this->cache->getMulti( $keysWarmUp );
1986 $warmupCache += array_fill_keys( $keysWarmUp, false );
1987
1988 return $warmupCache;
1989 }
1990 }