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