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