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