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