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