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