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