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