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