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