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