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