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