Merge "Fix call to non-existing TempFSFileFactory::getTempFSFile()"
[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 */
1309 private function fetchOrRegenerate( $key, $ttl, $callback, array $opts ) {
1310 $checkKeys = $opts['checkKeys'] ?? [];
1311 $graceTTL = $opts['graceTTL'] ?? self::GRACE_TTL_NONE;
1312 $minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
1313 $hotTTR = $opts['hotTTR'] ?? self::HOT_TTR;
1314 $lowTTL = $opts['lowTTL'] ?? min( self::LOW_TTL, $ttl );
1315 $ageNew = $opts['ageNew'] ?? self::AGE_NEW;
1316 $touchedCb = $opts['touchedCallback'] ?? null;
1317 $initialTime = $this->getCurrentTime();
1318
1319 $kClass = $this->determineKeyClassForStats( $key );
1320
1321 // Get the current key value and its metadata
1322 $curTTL = self::PASS_BY_REF;
1323 $curInfo = self::PASS_BY_REF; /** @var array $curInfo */
1324 $curValue = $this->get( $key, $curTTL, $checkKeys, $curInfo );
1325 // Apply any $touchedCb invalidation timestamp to get the "last purge timestamp"
1326 list( $curTTL, $LPT ) = $this->resolveCTL( $curValue, $curTTL, $curInfo, $touchedCb );
1327 // Use the cached value if it exists and is not due for synchronous regeneration
1328 if (
1329 $this->isValid( $curValue, $curInfo['asOf'], $minAsOf ) &&
1330 $this->isAliveOrInGracePeriod( $curTTL, $graceTTL )
1331 ) {
1332 $preemptiveRefresh = (
1333 $this->worthRefreshExpiring( $curTTL, $lowTTL ) ||
1334 $this->worthRefreshPopular( $curInfo['asOf'], $ageNew, $hotTTR, $initialTime )
1335 );
1336 if ( !$preemptiveRefresh ) {
1337 $this->stats->increment( "wanobjectcache.$kClass.hit.good" );
1338
1339 return [ $curValue, $curInfo['version'], $curInfo['asOf'] ];
1340 } elseif ( $this->scheduleAsyncRefresh( $key, $ttl, $callback, $opts ) ) {
1341 $this->stats->increment( "wanobjectcache.$kClass.hit.refresh" );
1342
1343 return [ $curValue, $curInfo['version'], $curInfo['asOf'] ];
1344 }
1345 }
1346
1347 // Determine if there is stale or volatile cached value that is still usable
1348 $isKeyTombstoned = ( $curInfo['tombAsOf'] !== null );
1349 if ( $isKeyTombstoned ) {
1350 // Key is write-holed; use the (volatile) interim key as an alternative
1351 list( $possValue, $possInfo ) = $this->getInterimValue( $key, $minAsOf );
1352 // Update the "last purge time" since the $touchedCb timestamp depends on $value
1353 $LPT = $this->resolveTouched( $possValue, $LPT, $touchedCb );
1354 } else {
1355 $possValue = $curValue;
1356 $possInfo = $curInfo;
1357 }
1358
1359 // Avoid overhead from callback runs, regeneration locks, and cache sets during
1360 // hold-off periods for the key by reusing very recently generated cached values
1361 if (
1362 $this->isValid( $possValue, $possInfo['asOf'], $minAsOf, $LPT ) &&
1363 $this->isVolatileValueAgeNegligible( $initialTime - $possInfo['asOf'] )
1364 ) {
1365 $this->stats->increment( "wanobjectcache.$kClass.hit.volatile" );
1366
1367 return [ $possValue, $possInfo['version'], $curInfo['asOf'] ];
1368 }
1369
1370 $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
1371 $busyValue = $opts['busyValue'] ?? null;
1372 $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
1373 $version = $opts['version'] ?? null;
1374
1375 // Determine whether one thread per datacenter should handle regeneration at a time
1376 $useRegenerationLock =
1377 // Note that since tombstones no-op set(), $lockTSE and $curTTL cannot be used to
1378 // deduce the key hotness because |$curTTL| will always keep increasing until the
1379 // tombstone expires or is overwritten by a new tombstone. Also, even if $lockTSE
1380 // is not set, constant regeneration of a key for the tombstone lifetime might be
1381 // very expensive. Assume tombstoned keys are possibly hot in order to reduce
1382 // the risk of high regeneration load after the delete() method is called.
1383 $isKeyTombstoned ||
1384 // Assume a key is hot if requested soon ($lockTSE seconds) after invalidation.
1385 // This avoids stampedes when timestamps from $checkKeys/$touchedCb bump.
1386 ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE ) ||
1387 // Assume a key is hot if there is no value and a busy fallback is given.
1388 // This avoids stampedes on eviction or preemptive regeneration taking too long.
1389 ( $busyValue !== null && $possValue === false );
1390
1391 // If a regeneration lock is required, threads that do not get the lock will try to use
1392 // the stale value, the interim value, or the $busyValue placeholder, in that order. If
1393 // none of those are set then all threads will bypass the lock and regenerate the value.
1394 $hasLock = $useRegenerationLock && $this->claimStampedeLock( $key );
1395 if ( $useRegenerationLock && !$hasLock ) {
1396 if ( $this->isValid( $possValue, $possInfo['asOf'], $minAsOf ) ) {
1397 $this->stats->increment( "wanobjectcache.$kClass.hit.stale" );
1398
1399 return [ $possValue, $possInfo['version'], $curInfo['asOf'] ];
1400 } elseif ( $busyValue !== null ) {
1401 $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1402 $this->stats->increment( "wanobjectcache.$kClass.$miss.busy" );
1403
1404 return [ $this->resolveBusyValue( $busyValue ), $version, $curInfo['asOf'] ];
1405 }
1406 }
1407
1408 // Generate the new value given any prior value with a matching version
1409 $setOpts = [];
1410 $preCallbackTime = $this->getCurrentTime();
1411 ++$this->callbackDepth;
1412 try {
1413 $value = $callback(
1414 ( $curInfo['version'] === $version ) ? $curValue : false,
1415 $ttl,
1416 $setOpts,
1417 ( $curInfo['version'] === $version ) ? $curInfo['asOf'] : null
1418 );
1419 } finally {
1420 --$this->callbackDepth;
1421 }
1422 $postCallbackTime = $this->getCurrentTime();
1423
1424 // How long it took to fetch, validate, and generate the value
1425 $elapsed = max( $postCallbackTime - $initialTime, 0.0 );
1426
1427 // Attempt to save the newly generated value if applicable
1428 if (
1429 // Callback yielded a cacheable value
1430 ( $value !== false && $ttl >= 0 ) &&
1431 // Current thread was not raced out of a regeneration lock or key is tombstoned
1432 ( !$useRegenerationLock || $hasLock || $isKeyTombstoned ) &&
1433 // Key does not appear to be undergoing a set() stampede
1434 $this->checkAndSetCooloff( $key, $kClass, $elapsed, $lockTSE, $hasLock )
1435 ) {
1436 // How long it took to generate the value
1437 $walltime = max( $postCallbackTime - $preCallbackTime, 0.0 );
1438 $this->stats->timing( "wanobjectcache.$kClass.regen_walltime", 1e3 * $walltime );
1439 // If the key is write-holed then use the (volatile) interim key as an alternative
1440 if ( $isKeyTombstoned ) {
1441 $this->setInterimValue( $key, $value, $lockTSE, $version, $walltime );
1442 } else {
1443 $finalSetOpts = [
1444 'since' => $setOpts['since'] ?? $preCallbackTime,
1445 'version' => $version,
1446 'staleTTL' => $staleTTL,
1447 'lockTSE' => $lockTSE, // informs lag vs performance trade-offs
1448 'creating' => ( $curValue === false ), // optimization
1449 'walltime' => $walltime
1450 ] + $setOpts;
1451 $this->set( $key, $value, $ttl, $finalSetOpts );
1452 }
1453 }
1454
1455 $this->yieldStampedeLock( $key, $hasLock );
1456
1457 $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1458 $this->stats->increment( "wanobjectcache.$kClass.$miss.compute" );
1459
1460 return [ $value, $version, $curInfo['asOf'] ];
1461 }
1462
1463 /**
1464 * @param string $key
1465 * @return bool Success
1466 */
1467 private function claimStampedeLock( $key ) {
1468 // Note that locking is not bypassed due to I/O errors; this avoids stampedes
1469 return $this->cache->add( self::$MUTEX_KEY_PREFIX . $key, 1, self::$LOCK_TTL );
1470 }
1471
1472 /**
1473 * @param string $key
1474 * @param bool $hasLock
1475 */
1476 private function yieldStampedeLock( $key, $hasLock ) {
1477 if ( $hasLock ) {
1478 // The backend might be a mcrouter proxy set to broadcast DELETE to *all* the local
1479 // datacenter cache servers via OperationSelectorRoute (for increased consistency).
1480 // Since that would be excessive for these locks, use TOUCH to expire the key.
1481 $this->cache->changeTTL( self::$MUTEX_KEY_PREFIX . $key, $this->getCurrentTime() - 60 );
1482 }
1483 }
1484
1485 /**
1486 * @param float $age Age of volatile/interim key in seconds
1487 * @return bool Whether the age of a volatile value is negligible
1488 */
1489 private function isVolatileValueAgeNegligible( $age ) {
1490 return ( $age < mt_rand( self::$RECENT_SET_LOW_MS, self::$RECENT_SET_HIGH_MS ) / 1e3 );
1491 }
1492
1493 /**
1494 * @param string $key
1495 * @param string $kClass
1496 * @param float $elapsed Seconds spent regenerating the value
1497 * @param float $lockTSE
1498 * @param bool $hasLock
1499 * @return bool Whether it is OK to proceed with a key set operation
1500 */
1501 private function checkAndSetCooloff( $key, $kClass, $elapsed, $lockTSE, $hasLock ) {
1502 $this->stats->timing( "wanobjectcache.$kClass.regen_set_delay", 1e3 * $elapsed );
1503
1504 // If $lockTSE is set, the lock was bypassed because there was no stale/interim value,
1505 // and $elapsed indicates that regeration is slow, then there is a risk of set()
1506 // stampedes with large blobs. With a typical scale-out infrastructure, CPU and query
1507 // load from $callback invocations is distributed among appservers and replica DBs,
1508 // but cache operations for a given key route to a single cache server (e.g. striped
1509 // consistent hashing).
1510 if ( $lockTSE < 0 || $hasLock ) {
1511 return true; // either not a priori hot or thread has the lock
1512 } elseif ( $elapsed <= self::$SET_DELAY_HIGH_MS * 1e3 ) {
1513 return true; // not enough time for threads to pile up
1514 }
1515
1516 $this->cache->clearLastError();
1517 if (
1518 !$this->cache->add( self::$COOLOFF_KEY_PREFIX . $key, 1, self::$COOLOFF_TTL ) &&
1519 // Don't treat failures due to I/O errors as the key being in cooloff
1520 $this->cache->getLastError() === BagOStuff::ERR_NONE
1521 ) {
1522 $this->stats->increment( "wanobjectcache.$kClass.cooloff_bounce" );
1523
1524 return false;
1525 }
1526
1527 return true;
1528 }
1529
1530 /**
1531 * @param mixed $value
1532 * @param float|null $curTTL
1533 * @param array $curInfo
1534 * @param callable|null $touchedCallback
1535 * @return array (current time left or null, UNIX timestamp of last purge or null)
1536 * @note Callable type hints are not used to avoid class-autoloading
1537 */
1538 private function resolveCTL( $value, $curTTL, $curInfo, $touchedCallback ) {
1539 if ( $touchedCallback === null || $value === false ) {
1540 return [ $curTTL, max( $curInfo['tombAsOf'], $curInfo['lastCKPurge'] ) ];
1541 }
1542
1543 $touched = $touchedCallback( $value );
1544 if ( $touched !== null && $touched >= $curInfo['asOf'] ) {
1545 $curTTL = min( $curTTL, self::$TINY_NEGATIVE, $curInfo['asOf'] - $touched );
1546 }
1547
1548 return [ $curTTL, max( $curInfo['tombAsOf'], $curInfo['lastCKPurge'], $touched ) ];
1549 }
1550
1551 /**
1552 * @param mixed $value
1553 * @param float|null $lastPurge
1554 * @param callable|null $touchedCallback
1555 * @return float|null UNIX timestamp of last purge or null
1556 * @note Callable type hints are not used to avoid class-autoloading
1557 */
1558 private function resolveTouched( $value, $lastPurge, $touchedCallback ) {
1559 return ( $touchedCallback === null || $value === false )
1560 ? $lastPurge // nothing to derive the "touched timestamp" from
1561 : max( $touchedCallback( $value ), $lastPurge );
1562 }
1563
1564 /**
1565 * @param string $key
1566 * @param float $minAsOf Minimum acceptable "as of" timestamp
1567 * @return array (cached value or false, cache key metadata map)
1568 */
1569 private function getInterimValue( $key, $minAsOf ) {
1570 $now = $this->getCurrentTime();
1571
1572 if ( $this->useInterimHoldOffCaching ) {
1573 $wrapped = $this->cache->get( self::$INTERIM_KEY_PREFIX . $key );
1574
1575 list( $value, $keyInfo ) = $this->unwrap( $wrapped, $now );
1576 if ( $this->isValid( $value, $keyInfo['asOf'], $minAsOf ) ) {
1577 return [ $value, $keyInfo ];
1578 }
1579 }
1580
1581 return $this->unwrap( false, $now );
1582 }
1583
1584 /**
1585 * @param string $key
1586 * @param mixed $value
1587 * @param int $ttl
1588 * @param int|null $version Value version number
1589 * @param float $walltime How long it took to generate the value in seconds
1590 */
1591 private function setInterimValue( $key, $value, $ttl, $version, $walltime ) {
1592 $ttl = max( self::$INTERIM_KEY_TTL, (int)$ttl );
1593
1594 $wrapped = $this->wrap( $value, $ttl, $version, $this->getCurrentTime(), $walltime );
1595 $this->cache->merge(
1596 self::$INTERIM_KEY_PREFIX . $key,
1597 function () use ( $wrapped ) {
1598 return $wrapped;
1599 },
1600 $ttl,
1601 1
1602 );
1603 }
1604
1605 /**
1606 * @param mixed $busyValue
1607 * @return mixed
1608 */
1609 private function resolveBusyValue( $busyValue ) {
1610 return ( $busyValue instanceof Closure ) ? $busyValue() : $busyValue;
1611 }
1612
1613 /**
1614 * Method to fetch multiple cache keys at once with regeneration
1615 *
1616 * This works the same as getWithSetCallback() except:
1617 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1618 * - b) The $callback argument expects a callback taking the following arguments:
1619 * - $id: ID of an entity to query
1620 * - $oldValue : the prior cache value or false if none was present
1621 * - &$ttl : a reference to the new value TTL in seconds
1622 * - &$setOpts : a reference to options for set() which can be altered
1623 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present
1624 * Aside from the additional $id argument, the other arguments function the same
1625 * way they do in getWithSetCallback().
1626 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1627 *
1628 * @see WANObjectCache::getWithSetCallback()
1629 * @see WANObjectCache::getMultiWithUnionSetCallback()
1630 *
1631 * Example usage:
1632 * @code
1633 * $rows = $cache->getMultiWithSetCallback(
1634 * // Map of cache keys to entity IDs
1635 * $cache->makeMultiKeys(
1636 * $this->fileVersionIds(),
1637 * function ( $id ) use ( $cache ) {
1638 * return $cache->makeKey( 'file-version', $id );
1639 * }
1640 * ),
1641 * // Time-to-live (in seconds)
1642 * $cache::TTL_DAY,
1643 * // Function that derives the new key value
1644 * function ( $id, $oldValue, &$ttl, array &$setOpts ) {
1645 * $dbr = wfGetDB( DB_REPLICA );
1646 * // Account for any snapshot/replica DB lag
1647 * $setOpts += Database::getCacheSetOptions( $dbr );
1648 *
1649 * // Load the row for this file
1650 * $queryInfo = File::getQueryInfo();
1651 * $row = $dbr->selectRow(
1652 * $queryInfo['tables'],
1653 * $queryInfo['fields'],
1654 * [ 'id' => $id ],
1655 * __METHOD__,
1656 * [],
1657 * $queryInfo['joins']
1658 * );
1659 *
1660 * return $row ? (array)$row : false;
1661 * },
1662 * [
1663 * // Process cache for 30 seconds
1664 * 'pcTTL' => 30,
1665 * // Use a dedicated 500 item cache (initialized on-the-fly)
1666 * 'pcGroup' => 'file-versions:500'
1667 * ]
1668 * );
1669 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1670 * @endcode
1671 *
1672 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1673 * @param int $ttl Seconds to live for key updates
1674 * @param callable $callback Callback the yields entity regeneration callbacks
1675 * @param array $opts Options map
1676 * @return mixed[] Map of (cache key => value) in the same order as $keyedIds
1677 * @since 1.28
1678 */
1679 final public function getMultiWithSetCallback(
1680 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1681 ) {
1682 // Load required keys into process cache in one go
1683 $this->warmupCache = $this->getRawKeysForWarmup(
1684 $this->getNonProcessCachedMultiKeys( $keyedIds, $opts ),
1685 $opts['checkKeys'] ?? []
1686 );
1687 $this->warmupKeyMisses = 0;
1688
1689 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1690 $id = null; // current entity ID
1691 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf ) use ( $callback, &$id ) {
1692 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1693 };
1694
1695 $values = [];
1696 foreach ( $keyedIds as $key => $id ) { // preserve order
1697 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1698 }
1699
1700 $this->warmupCache = [];
1701
1702 return $values;
1703 }
1704
1705 /**
1706 * Method to fetch/regenerate multiple cache keys at once
1707 *
1708 * This works the same as getWithSetCallback() except:
1709 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1710 * - b) The $callback argument expects a callback returning a map of (ID => new value)
1711 * for all entity IDs in $ids and it takes the following arguments:
1712 * - $ids: a list of entity IDs that require cache regeneration
1713 * - &$ttls: a reference to the (entity ID => new TTL) map
1714 * - &$setOpts: a reference to options for set() which can be altered
1715 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1716 * - d) The "lockTSE" and "busyValue" options are ignored
1717 *
1718 * @see WANObjectCache::getWithSetCallback()
1719 * @see WANObjectCache::getMultiWithSetCallback()
1720 *
1721 * Example usage:
1722 * @code
1723 * $rows = $cache->getMultiWithUnionSetCallback(
1724 * // Map of cache keys to entity IDs
1725 * $cache->makeMultiKeys(
1726 * $this->fileVersionIds(),
1727 * function ( $id ) use ( $cache ) {
1728 * return $cache->makeKey( 'file-version', $id );
1729 * }
1730 * ),
1731 * // Time-to-live (in seconds)
1732 * $cache::TTL_DAY,
1733 * // Function that derives the new key value
1734 * function ( array $ids, array &$ttls, array &$setOpts ) {
1735 * $dbr = wfGetDB( DB_REPLICA );
1736 * // Account for any snapshot/replica DB lag
1737 * $setOpts += Database::getCacheSetOptions( $dbr );
1738 *
1739 * // Load the rows for these files
1740 * $rows = [];
1741 * $queryInfo = File::getQueryInfo();
1742 * $res = $dbr->select(
1743 * $queryInfo['tables'],
1744 * $queryInfo['fields'],
1745 * [ 'id' => $ids ],
1746 * __METHOD__,
1747 * [],
1748 * $queryInfo['joins']
1749 * );
1750 * foreach ( $res as $row ) {
1751 * $rows[$row->id] = $row;
1752 * $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
1753 * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
1754 * }
1755 *
1756 * return $rows;
1757 * },
1758 * ]
1759 * );
1760 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1761 * @endcode
1762 *
1763 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1764 * @param int $ttl Seconds to live for key updates
1765 * @param callable $callback Callback the yields entity regeneration callbacks
1766 * @param array $opts Options map
1767 * @return mixed[] Map of (cache key => value) in the same order as $keyedIds
1768 * @since 1.30
1769 */
1770 final public function getMultiWithUnionSetCallback(
1771 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1772 ) {
1773 $checkKeys = $opts['checkKeys'] ?? [];
1774 unset( $opts['lockTSE'] ); // incompatible
1775 unset( $opts['busyValue'] ); // incompatible
1776
1777 // Load required keys into process cache in one go
1778 $keysByIdGet = $this->getNonProcessCachedMultiKeys( $keyedIds, $opts );
1779 $this->warmupCache = $this->getRawKeysForWarmup( $keysByIdGet, $checkKeys );
1780 $this->warmupKeyMisses = 0;
1781
1782 // IDs of entities known to be in need of regeneration
1783 $idsRegen = [];
1784
1785 // Find out which keys are missing/deleted/stale
1786 $curTTLs = [];
1787 $asOfs = [];
1788 $curByKey = $this->getMulti( $keysByIdGet, $curTTLs, $checkKeys, $asOfs );
1789 foreach ( $keysByIdGet as $id => $key ) {
1790 if ( !array_key_exists( $key, $curByKey ) || $curTTLs[$key] < 0 ) {
1791 $idsRegen[] = $id;
1792 }
1793 }
1794
1795 // Run the callback to populate the regeneration value map for all required IDs
1796 $newSetOpts = [];
1797 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
1798 $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
1799
1800 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1801 $id = null; // current entity ID
1802 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1803 use ( $callback, &$id, $newValsById, $newTTLsById, $newSetOpts )
1804 {
1805 if ( array_key_exists( $id, $newValsById ) ) {
1806 // Value was already regerated as expected, so use the value in $newValsById
1807 $newValue = $newValsById[$id];
1808 $ttl = $newTTLsById[$id];
1809 $setOpts = $newSetOpts;
1810 } else {
1811 // Pre-emptive/popularity refresh and version mismatch cases are not detected
1812 // above and thus $newValsById has no entry. Run $callback on this single entity.
1813 $ttls = [ $id => $ttl ];
1814 $newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
1815 $ttl = $ttls[$id];
1816 }
1817
1818 return $newValue;
1819 };
1820
1821 // Run the cache-aside logic using warmupCache instead of persistent cache queries
1822 $values = [];
1823 foreach ( $keyedIds as $key => $id ) { // preserve order
1824 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1825 }
1826
1827 $this->warmupCache = [];
1828
1829 return $values;
1830 }
1831
1832 /**
1833 * Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1834 *
1835 * This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids
1836 * broadcasting in mcrouter setups and also avoids races with new tombstones.
1837 *
1838 * @param string $key Cache key
1839 * @param int $purgeTimestamp UNIX timestamp of purge
1840 * @param bool &$isStale Whether the key is stale
1841 * @return bool Success
1842 * @since 1.28
1843 */
1844 final public function reap( $key, $purgeTimestamp, &$isStale = false ) {
1845 $minAsOf = $purgeTimestamp + self::HOLDOFF_TTL;
1846 $wrapped = $this->cache->get( self::$VALUE_KEY_PREFIX . $key );
1847 if ( is_array( $wrapped ) && $wrapped[self::$FLD_TIME] < $minAsOf ) {
1848 $isStale = true;
1849 $this->logger->warning( "Reaping stale value key '$key'." );
1850 $ttlReap = self::HOLDOFF_TTL; // avoids races with tombstone creation
1851 $ok = $this->cache->changeTTL( self::$VALUE_KEY_PREFIX . $key, $ttlReap );
1852 if ( !$ok ) {
1853 $this->logger->error( "Could not complete reap of key '$key'." );
1854 }
1855
1856 return $ok;
1857 }
1858
1859 $isStale = false;
1860
1861 return true;
1862 }
1863
1864 /**
1865 * Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1866 *
1867 * @param string $key Cache key
1868 * @param int $purgeTimestamp UNIX timestamp of purge
1869 * @param bool &$isStale Whether the key is stale
1870 * @return bool Success
1871 * @since 1.28
1872 */
1873 final public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
1874 $purge = $this->parsePurgeValue( $this->cache->get( self::$TIME_KEY_PREFIX . $key ) );
1875 if ( $purge && $purge[self::$PURGE_TIME] < $purgeTimestamp ) {
1876 $isStale = true;
1877 $this->logger->warning( "Reaping stale check key '$key'." );
1878 $ok = $this->cache->changeTTL( self::$TIME_KEY_PREFIX . $key, self::TTL_SECOND );
1879 if ( !$ok ) {
1880 $this->logger->error( "Could not complete reap of check key '$key'." );
1881 }
1882
1883 return $ok;
1884 }
1885
1886 $isStale = false;
1887
1888 return false;
1889 }
1890
1891 /**
1892 * @see BagOStuff::makeKey()
1893 * @param string $class Key class
1894 * @param string ...$components Key components (starting with a key collection name)
1895 * @return string Colon-delimited list of $keyspace followed by escaped components
1896 * @since 1.27
1897 */
1898 public function makeKey( $class, ...$components ) {
1899 return $this->cache->makeKey( ...func_get_args() );
1900 }
1901
1902 /**
1903 * @see BagOStuff::makeGlobalKey()
1904 * @param string $class Key class
1905 * @param string ...$components Key components (starting with a key collection name)
1906 * @return string Colon-delimited list of $keyspace followed by escaped components
1907 * @since 1.27
1908 */
1909 public function makeGlobalKey( $class, ...$components ) {
1910 return $this->cache->makeGlobalKey( ...func_get_args() );
1911 }
1912
1913 /**
1914 * Hash a possibly long string into a suitable component for makeKey()/makeGlobalKey()
1915 *
1916 * @param string $component A raw component used in building a cache key
1917 * @return string 64 character HMAC using a stable secret for public collision resistance
1918 * @since 1.34
1919 */
1920 public function hash256( $component ) {
1921 return hash_hmac( 'sha256', $component, $this->secret );
1922 }
1923
1924 /**
1925 * Get an iterator of (cache key => entity ID) for a list of entity IDs
1926 *
1927 * The callback takes an ID string and returns a key via makeKey()/makeGlobalKey().
1928 * There should be no network nor filesystem I/O used in the callback. The entity
1929 * ID/key mapping must be 1:1 or an exception will be thrown. If hashing is needed,
1930 * then use the hash256() method.
1931 *
1932 * Example usage for the default keyspace:
1933 * @code
1934 * $keyedIds = $cache->makeMultiKeys(
1935 * $modules,
1936 * function ( $module ) use ( $cache ) {
1937 * return $cache->makeKey( 'module-info', $module );
1938 * }
1939 * );
1940 * @endcode
1941 *
1942 * Example usage for mixed default and global keyspace:
1943 * @code
1944 * $keyedIds = $cache->makeMultiKeys(
1945 * $filters,
1946 * function ( $filter ) use ( $cache ) {
1947 * return ( strpos( $filter, 'central:' ) === 0 )
1948 * ? $cache->makeGlobalKey( 'regex-filter', $filter )
1949 * : $cache->makeKey( 'regex-filter', $filter )
1950 * }
1951 * );
1952 * @endcode
1953 *
1954 * Example usage with hashing:
1955 * @code
1956 * $keyedIds = $cache->makeMultiKeys(
1957 * $urls,
1958 * function ( $url ) use ( $cache ) {
1959 * return $cache->makeKey( 'url-info', $cache->hash256( $url ) );
1960 * }
1961 * );
1962 * @endcode
1963 *
1964 * @see WANObjectCache::makeKey()
1965 * @see WANObjectCache::makeGlobalKey()
1966 * @see WANObjectCache::hash256()
1967 *
1968 * @param string[]|int[] $ids List of entity IDs
1969 * @param callable $keyCallback Function returning makeKey()/makeGlobalKey() on the input ID
1970 * @return ArrayIterator Iterator of (cache key => ID); order of $ids is preserved
1971 * @throws UnexpectedValueException
1972 * @since 1.28
1973 */
1974 final public function makeMultiKeys( array $ids, $keyCallback ) {
1975 $idByKey = [];
1976 foreach ( $ids as $id ) {
1977 // Discourage triggering of automatic makeKey() hashing in some backends
1978 if ( strlen( $id ) > 64 ) {
1979 $this->logger->warning( __METHOD__ . ": long ID '$id'; use hash256()" );
1980 }
1981 $key = $keyCallback( $id, $this );
1982 // Edge case: ignore key collisions due to duplicate $ids like "42" and 42
1983 if ( !isset( $idByKey[$key] ) ) {
1984 $idByKey[$key] = $id;
1985 } elseif ( (string)$id !== (string)$idByKey[$key] ) {
1986 throw new UnexpectedValueException(
1987 "Cache key collision; IDs ('$id','{$idByKey[$key]}') map to '$key'"
1988 );
1989 }
1990 }
1991
1992 return new ArrayIterator( $idByKey );
1993 }
1994
1995 /**
1996 * Get an (ID => value) map from (i) a non-unique list of entity IDs, and (ii) the list
1997 * of corresponding entity values by first appearance of each ID in the entity ID list
1998 *
1999 * For use with getMultiWithSetCallback() and getMultiWithUnionSetCallback().
2000 *
2001 * *Only* use this method if the entity ID/key mapping is trivially 1:1 without exception.
2002 * Key generation method must utitilize the *full* entity ID in the key (not a hash of it).
2003 *
2004 * Example usage:
2005 * @code
2006 * $poems = $cache->getMultiWithSetCallback(
2007 * $cache->makeMultiKeys(
2008 * $uuids,
2009 * function ( $uuid ) use ( $cache ) {
2010 * return $cache->makeKey( 'poem', $uuid );
2011 * }
2012 * ),
2013 * $cache::TTL_DAY,
2014 * function ( $uuid ) use ( $url ) {
2015 * return $this->http->run( [ 'method' => 'GET', 'url' => "$url/$uuid" ] );
2016 * }
2017 * );
2018 * $poemsByUUID = $cache->multiRemap( $uuids, $poems );
2019 * @endcode
2020 *
2021 * @see WANObjectCache::makeMultiKeys()
2022 * @see WANObjectCache::getMultiWithSetCallback()
2023 * @see WANObjectCache::getMultiWithUnionSetCallback()
2024 *
2025 * @param string[]|int[] $ids Entity ID list makeMultiKeys()
2026 * @param mixed[] $res Result of getMultiWithSetCallback()/getMultiWithUnionSetCallback()
2027 * @return mixed[] Map of (ID => value); order of $ids is preserved
2028 * @since 1.34
2029 */
2030 final public function multiRemap( array $ids, array $res ) {
2031 if ( count( $ids ) !== count( $res ) ) {
2032 // If makeMultiKeys() is called on a list of non-unique IDs, then the resulting
2033 // ArrayIterator will have less entries due to "first appearance" de-duplication
2034 $ids = array_keys( array_flip( $ids ) );
2035 if ( count( $ids ) !== count( $res ) ) {
2036 throw new UnexpectedValueException( "Multi-key result does not match ID list" );
2037 }
2038 }
2039
2040 return array_combine( $ids, $res );
2041 }
2042
2043 /**
2044 * Get the "last error" registered; clearLastError() should be called manually
2045 * @return int ERR_* class constant for the "last error" registry
2046 */
2047 final public function getLastError() {
2048 $code = $this->cache->getLastError();
2049 switch ( $code ) {
2050 case BagOStuff::ERR_NONE:
2051 return self::ERR_NONE;
2052 case BagOStuff::ERR_NO_RESPONSE:
2053 return self::ERR_NO_RESPONSE;
2054 case BagOStuff::ERR_UNREACHABLE:
2055 return self::ERR_UNREACHABLE;
2056 default:
2057 return self::ERR_UNEXPECTED;
2058 }
2059 }
2060
2061 /**
2062 * Clear the "last error" registry
2063 */
2064 final public function clearLastError() {
2065 $this->cache->clearLastError();
2066 }
2067
2068 /**
2069 * Clear the in-process caches; useful for testing
2070 *
2071 * @since 1.27
2072 */
2073 public function clearProcessCache() {
2074 $this->processCaches = [];
2075 }
2076
2077 /**
2078 * Enable or disable the use of brief caching for tombstoned keys
2079 *
2080 * When a key is purged via delete(), there normally is a period where caching
2081 * is hold-off limited to an extremely short time. This method will disable that
2082 * caching, forcing the callback to run for any of:
2083 * - WANObjectCache::getWithSetCallback()
2084 * - WANObjectCache::getMultiWithSetCallback()
2085 * - WANObjectCache::getMultiWithUnionSetCallback()
2086 *
2087 * This is useful when both:
2088 * - a) the database used by the callback is known to be up-to-date enough
2089 * for some particular purpose (e.g. replica DB has applied transaction X)
2090 * - b) the caller needs to exploit that fact, and therefore needs to avoid the
2091 * use of inherently volatile and possibly stale interim keys
2092 *
2093 * @see WANObjectCache::delete()
2094 * @param bool $enabled Whether to enable interim caching
2095 * @since 1.31
2096 */
2097 final public function useInterimHoldOffCaching( $enabled ) {
2098 $this->useInterimHoldOffCaching = $enabled;
2099 }
2100
2101 /**
2102 * @param int $flag ATTR_* class constant
2103 * @return int QOS_* class constant
2104 * @since 1.28
2105 */
2106 public function getQoS( $flag ) {
2107 return $this->cache->getQoS( $flag );
2108 }
2109
2110 /**
2111 * Get a TTL that is higher for objects that have not changed recently
2112 *
2113 * This is useful for keys that get explicit purges and DB or purge relay
2114 * lag is a potential concern (especially how it interacts with CDN cache)
2115 *
2116 * Example usage:
2117 * @code
2118 * // Last-modified time of page
2119 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
2120 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
2121 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
2122 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
2123 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
2124 * @endcode
2125 *
2126 * Another use case is when there are no applicable "last modified" fields in the DB,
2127 * and there are too many dependencies for explicit purges to be viable, and the rate of
2128 * change to relevant content is unstable, and it is highly valued to have the cached value
2129 * be as up-to-date as possible.
2130 *
2131 * Example usage:
2132 * @code
2133 * $query = "<some complex query>";
2134 * $idListFromComplexQuery = $cache->getWithSetCallback(
2135 * $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
2136 * GraphQueryClass::STARTING_TTL,
2137 * function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
2138 * $gdb = $this->getReplicaGraphDbConnection();
2139 * // Account for any snapshot/replica DB lag
2140 * $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
2141 *
2142 * $newList = iterator_to_array( $gdb->query( $query ) );
2143 * sort( $newList, SORT_NUMERIC ); // normalize
2144 *
2145 * $minTTL = GraphQueryClass::MIN_TTL;
2146 * $maxTTL = GraphQueryClass::MAX_TTL;
2147 * if ( $oldValue !== false ) {
2148 * // Note that $oldAsOf is the last time this callback ran
2149 * $ttl = ( $newList === $oldValue )
2150 * // No change: cache for 150% of the age of $oldValue
2151 * ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
2152 * // Changed: cache for 50% of the age of $oldValue
2153 * : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
2154 * }
2155 *
2156 * return $newList;
2157 * },
2158 * [
2159 * // Keep stale values around for doing comparisons for TTL calculations.
2160 * // High values improve long-tail keys hit-rates, though might waste space.
2161 * 'staleTTL' => GraphQueryClass::GRACE_TTL
2162 * ]
2163 * );
2164 * @endcode
2165 *
2166 * @param int|float $mtime UNIX timestamp
2167 * @param int $maxTTL Maximum TTL (seconds)
2168 * @param int $minTTL Minimum TTL (seconds); Default: 30
2169 * @param float $factor Value in the range (0,1); Default: .2
2170 * @return int Adaptive TTL
2171 * @since 1.28
2172 */
2173 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
2174 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
2175 $mtime = (int)$mtime; // handle fractional seconds and string integers
2176 }
2177
2178 if ( !is_int( $mtime ) || $mtime <= 0 ) {
2179 return $minTTL; // no last-modified time provided
2180 }
2181
2182 $age = $this->getCurrentTime() - $mtime;
2183
2184 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
2185 }
2186
2187 /**
2188 * @return int Number of warmup key cache misses last round
2189 * @since 1.30
2190 */
2191 final public function getWarmupKeyMisses() {
2192 return $this->warmupKeyMisses;
2193 }
2194
2195 /**
2196 * Do the actual async bus purge of a key
2197 *
2198 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
2199 *
2200 * @param string $key Cache key
2201 * @param int $ttl Seconds to keep the tombstone around
2202 * @param int $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
2203 * @return bool Success
2204 */
2205 protected function relayPurge( $key, $ttl, $holdoff ) {
2206 if ( $this->mcrouterAware ) {
2207 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
2208 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
2209 $ok = $this->cache->set(
2210 "/*/{$this->cluster}/{$key}",
2211 $this->makePurgeValue( $this->getCurrentTime(), $holdoff ),
2212 $ttl
2213 );
2214 } else {
2215 // Some other proxy handles broadcasting or there is only one datacenter
2216 $ok = $this->cache->set(
2217 $key,
2218 $this->makePurgeValue( $this->getCurrentTime(), $holdoff ),
2219 $ttl
2220 );
2221 }
2222
2223 return $ok;
2224 }
2225
2226 /**
2227 * Do the actual async bus delete of a key
2228 *
2229 * @param string $key Cache key
2230 * @return bool Success
2231 */
2232 protected function relayDelete( $key ) {
2233 if ( $this->mcrouterAware ) {
2234 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
2235 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
2236 $ok = $this->cache->delete( "/*/{$this->cluster}/{$key}" );
2237 } else {
2238 // Some other proxy handles broadcasting or there is only one datacenter
2239 $ok = $this->cache->delete( $key );
2240 }
2241
2242 return $ok;
2243 }
2244
2245 /**
2246 * @param string $key
2247 * @param int $ttl Seconds to live
2248 * @param callable $callback
2249 * @param array $opts
2250 * @return bool Success
2251 * @note Callable type hints are not used to avoid class-autoloading
2252 */
2253 private function scheduleAsyncRefresh( $key, $ttl, $callback, $opts ) {
2254 if ( !$this->asyncHandler ) {
2255 return false;
2256 }
2257 // Update the cache value later, such during post-send of an HTTP request
2258 $func = $this->asyncHandler;
2259 $func( function () use ( $key, $ttl, $callback, $opts ) {
2260 $opts['minAsOf'] = INF; // force a refresh
2261 $this->fetchOrRegenerate( $key, $ttl, $callback, $opts );
2262 } );
2263
2264 return true;
2265 }
2266
2267 /**
2268 * Check if a key is fresh or in the grace window and thus due for randomized reuse
2269 *
2270 * If $curTTL > 0 (e.g. not expired) this returns true. Otherwise, the chance of returning
2271 * true decrease steadily from 100% to 0% as the |$curTTL| moves from 0 to $graceTTL seconds.
2272 * This handles widely varying levels of cache access traffic.
2273 *
2274 * If $curTTL <= -$graceTTL (e.g. already expired), then this returns false.
2275 *
2276 * @param float $curTTL Approximate TTL left on the key if present
2277 * @param int $graceTTL Consider using stale values if $curTTL is greater than this
2278 * @return bool
2279 */
2280 private function isAliveOrInGracePeriod( $curTTL, $graceTTL ) {
2281 if ( $curTTL > 0 ) {
2282 return true;
2283 } elseif ( $graceTTL <= 0 ) {
2284 return false;
2285 }
2286
2287 $ageStale = abs( $curTTL ); // seconds of staleness
2288 $curGTTL = ( $graceTTL - $ageStale ); // current grace-time-to-live
2289 if ( $curGTTL <= 0 ) {
2290 return false; // already out of grace period
2291 }
2292
2293 // Chance of using a stale value is the complement of the chance of refreshing it
2294 return !$this->worthRefreshExpiring( $curGTTL, $graceTTL );
2295 }
2296
2297 /**
2298 * Check if a key is nearing expiration and thus due for randomized regeneration
2299 *
2300 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance of returning true
2301 * increases steadily from 0% to 100% as the $curTTL moves from $lowTTL to 0 seconds.
2302 * This handles widely varying levels of cache access traffic.
2303 *
2304 * If $curTTL <= 0 (e.g. already expired), then this returns false.
2305 *
2306 * @param float $curTTL Approximate TTL left on the key if present
2307 * @param float $lowTTL Consider a refresh when $curTTL is less than this
2308 * @return bool
2309 */
2310 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
2311 if ( $lowTTL <= 0 ) {
2312 return false;
2313 } elseif ( $curTTL >= $lowTTL ) {
2314 return false;
2315 } elseif ( $curTTL <= 0 ) {
2316 return false;
2317 }
2318
2319 $chance = ( 1 - $curTTL / $lowTTL );
2320
2321 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
2322 }
2323
2324 /**
2325 * Check if a key is due for randomized regeneration due to its popularity
2326 *
2327 * This is used so that popular keys can preemptively refresh themselves for higher
2328 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
2329 * in cache with their high nominal TTL. This means popular keys keep good consistency,
2330 * whether the data changes frequently or not, and long-tail keys get to stay in cache
2331 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
2332 *
2333 * @param float $asOf UNIX timestamp of the value
2334 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
2335 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
2336 * @param float $now The current UNIX timestamp
2337 * @return bool
2338 */
2339 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
2340 if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
2341 return false;
2342 }
2343
2344 $age = $now - $asOf;
2345 $timeOld = $age - $ageNew;
2346 if ( $timeOld <= 0 ) {
2347 return false;
2348 }
2349
2350 $popularHitsPerSec = 1;
2351 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
2352 // Note that the "expected # of refreshes" for the ramp-up time range is half
2353 // of what it would be if P(refresh) was at its full value during that time range.
2354 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::$RAMPUP_TTL / 2, 1 );
2355 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
2356 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1 (by definition)
2357 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
2358 $chance = 1 / ( $popularHitsPerSec * $refreshWindowSec );
2359
2360 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
2361 $chance *= ( $timeOld <= self::$RAMPUP_TTL ) ? $timeOld / self::$RAMPUP_TTL : 1;
2362
2363 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
2364 }
2365
2366 /**
2367 * Check if $value is not false, versioned (if needed), and not older than $minTime (if set)
2368 *
2369 * @param array|bool $value
2370 * @param float $asOf The time $value was generated
2371 * @param float $minAsOf Minimum acceptable "as of" timestamp
2372 * @param float|null $purgeTime The last time the value was invalidated
2373 * @return bool
2374 */
2375 protected function isValid( $value, $asOf, $minAsOf, $purgeTime = null ) {
2376 // Avoid reading any key not generated after the latest delete() or touch
2377 $safeMinAsOf = max( $minAsOf, $purgeTime + self::$TINY_POSTIVE );
2378
2379 if ( $value === false ) {
2380 return false;
2381 } elseif ( $safeMinAsOf > 0 && $asOf < $minAsOf ) {
2382 return false;
2383 }
2384
2385 return true;
2386 }
2387
2388 /**
2389 * @param mixed $value
2390 * @param int $ttl Seconds to live or zero for "indefinite"
2391 * @param int|null $version Value version number or null if not versioned
2392 * @param float $now Unix Current timestamp just before calling set()
2393 * @param float $walltime How long it took to generate the value in seconds
2394 * @return array
2395 */
2396 private function wrap( $value, $ttl, $version, $now, $walltime ) {
2397 // Returns keys in ascending integer order for PHP7 array packing:
2398 // https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html
2399 $wrapped = [
2400 self::$FLD_FORMAT_VERSION => self::$VERSION,
2401 self::$FLD_VALUE => $value,
2402 self::$FLD_TTL => $ttl,
2403 self::$FLD_TIME => $now
2404 ];
2405 if ( $version !== null ) {
2406 $wrapped[self::$FLD_VALUE_VERSION] = $version;
2407 }
2408 if ( $walltime >= self::$GENERATION_SLOW_SEC ) {
2409 $wrapped[self::$FLD_GENERATION_TIME] = $walltime;
2410 }
2411
2412 return $wrapped;
2413 }
2414
2415 /**
2416 * @param array|string|bool $wrapped The entry at a cache key
2417 * @param float $now Unix Current timestamp (preferrably pre-query)
2418 * @return array (value or false if absent/tombstoned/malformed, value metadata map).
2419 * The cache key metadata includes the following metadata:
2420 * - asOf: UNIX timestamp of the value or null if there is no value
2421 * - curTTL: remaining time-to-live (negative if tombstoned) or null if there is no value
2422 * - version: value version number or null if the if there is no value
2423 * - tombAsOf: UNIX timestamp of the tombstone or null if there is no tombstone
2424 */
2425 private function unwrap( $wrapped, $now ) {
2426 $value = false;
2427 $info = [ 'asOf' => null, 'curTTL' => null, 'version' => null, 'tombAsOf' => null ];
2428
2429 if ( is_array( $wrapped ) ) {
2430 // Entry expected to be a cached value; validate it
2431 if (
2432 ( $wrapped[self::$FLD_FORMAT_VERSION] ?? null ) === self::$VERSION &&
2433 $wrapped[self::$FLD_TIME] >= $this->epoch
2434 ) {
2435 if ( $wrapped[self::$FLD_TTL] > 0 ) {
2436 // Get the approximate time left on the key
2437 $age = $now - $wrapped[self::$FLD_TIME];
2438 $curTTL = max( $wrapped[self::$FLD_TTL] - $age, 0.0 );
2439 } else {
2440 // Key had no TTL, so the time left is unbounded
2441 $curTTL = INF;
2442 }
2443 $value = $wrapped[self::$FLD_VALUE];
2444 $info['version'] = $wrapped[self::$FLD_VALUE_VERSION] ?? null;
2445 $info['asOf'] = $wrapped[self::$FLD_TIME];
2446 $info['curTTL'] = $curTTL;
2447 }
2448 } else {
2449 // Entry expected to be a tombstone; parse it
2450 $purge = $this->parsePurgeValue( $wrapped );
2451 if ( $purge !== false ) {
2452 // Tombstoned keys should always have a negative current $ttl
2453 $info['curTTL'] = min( $purge[self::$PURGE_TIME] - $now, self::$TINY_NEGATIVE );
2454 $info['tombAsOf'] = $purge[self::$PURGE_TIME];
2455 }
2456 }
2457
2458 return [ $value, $info ];
2459 }
2460
2461 /**
2462 * @param string[] $keys
2463 * @param string $prefix
2464 * @return string[] Prefix keys; the order of $keys is preserved
2465 */
2466 protected static function prefixCacheKeys( array $keys, $prefix ) {
2467 $res = [];
2468 foreach ( $keys as $key ) {
2469 $res[] = $prefix . $key;
2470 }
2471
2472 return $res;
2473 }
2474
2475 /**
2476 * @param string $key String of the format <scope>:<class>[:<class or variable>]...
2477 * @return string A collection name to describe this class of key
2478 */
2479 private function determineKeyClassForStats( $key ) {
2480 $parts = explode( ':', $key, 3 );
2481
2482 return $parts[1] ?? $parts[0]; // sanity
2483 }
2484
2485 /**
2486 * @param string|array|bool $value Possible string of the form "PURGED:<timestamp>:<holdoff>"
2487 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
2488 * or false if value isn't a valid purge value
2489 */
2490 private function parsePurgeValue( $value ) {
2491 if ( !is_string( $value ) ) {
2492 return false;
2493 }
2494
2495 $segments = explode( ':', $value, 3 );
2496 if (
2497 !isset( $segments[0] ) ||
2498 !isset( $segments[1] ) ||
2499 "{$segments[0]}:" !== self::$PURGE_VAL_PREFIX
2500 ) {
2501 return false;
2502 }
2503
2504 if ( !isset( $segments[2] ) ) {
2505 // Back-compat with old purge values without holdoff
2506 $segments[2] = self::HOLDOFF_TTL;
2507 }
2508
2509 if ( $segments[1] < $this->epoch ) {
2510 // Values this old are ignored
2511 return false;
2512 }
2513
2514 return [
2515 self::$PURGE_TIME => (float)$segments[1],
2516 self::$PURGE_HOLDOFF => (int)$segments[2],
2517 ];
2518 }
2519
2520 /**
2521 * @param float $timestamp
2522 * @param int $holdoff In seconds
2523 * @return string Wrapped purge value
2524 */
2525 private function makePurgeValue( $timestamp, $holdoff ) {
2526 return self::$PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
2527 }
2528
2529 /**
2530 * @param string $group
2531 * @return MapCacheLRU
2532 */
2533 private function getProcessCache( $group ) {
2534 if ( !isset( $this->processCaches[$group] ) ) {
2535 list( , $size ) = explode( ':', $group );
2536 $this->processCaches[$group] = new MapCacheLRU( (int)$size );
2537 }
2538
2539 return $this->processCaches[$group];
2540 }
2541
2542 /**
2543 * @param string $key
2544 * @param int $version
2545 * @return string
2546 */
2547 private function getProcessCacheKey( $key, $version ) {
2548 return $key . ' ' . (int)$version;
2549 }
2550
2551 /**
2552 * @param ArrayIterator $keys
2553 * @param array $opts
2554 * @return string[] Map of (ID => cache key)
2555 */
2556 private function getNonProcessCachedMultiKeys( ArrayIterator $keys, array $opts ) {
2557 $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
2558
2559 $keysMissing = [];
2560 if ( $pcTTL > 0 && $this->callbackDepth == 0 ) {
2561 $version = $opts['version'] ?? null;
2562 $pCache = $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY );
2563 foreach ( $keys as $key => $id ) {
2564 if ( !$pCache->has( $this->getProcessCacheKey( $key, $version ), $pcTTL ) ) {
2565 $keysMissing[$id] = $key;
2566 }
2567 }
2568 }
2569
2570 return $keysMissing;
2571 }
2572
2573 /**
2574 * @param string[] $keys
2575 * @param string[]|string[][] $checkKeys
2576 * @return string[] List of cache keys
2577 */
2578 private function getRawKeysForWarmup( array $keys, array $checkKeys ) {
2579 if ( !$keys ) {
2580 return [];
2581 }
2582
2583 $keysWarmUp = [];
2584 // Get all the value keys to fetch...
2585 foreach ( $keys as $key ) {
2586 $keysWarmUp[] = self::$VALUE_KEY_PREFIX . $key;
2587 }
2588 // Get all the check keys to fetch...
2589 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
2590 if ( is_int( $i ) ) {
2591 // Single check key that applies to all value keys
2592 $keysWarmUp[] = self::$TIME_KEY_PREFIX . $checkKeyOrKeys;
2593 } else {
2594 // List of check keys that apply to value key $i
2595 $keysWarmUp = array_merge(
2596 $keysWarmUp,
2597 self::prefixCacheKeys( $checkKeyOrKeys, self::$TIME_KEY_PREFIX )
2598 );
2599 }
2600 }
2601
2602 $warmupCache = $this->cache->getMulti( $keysWarmUp );
2603 $warmupCache += array_fill_keys( $keysWarmUp, false );
2604
2605 return $warmupCache;
2606 }
2607
2608 /**
2609 * @return float UNIX timestamp
2610 * @codeCoverageIgnore
2611 */
2612 protected function getCurrentTime() {
2613 if ( $this->wallClockOverride ) {
2614 return $this->wallClockOverride;
2615 }
2616
2617 $clockTime = (float)time(); // call this first
2618 // microtime() uses an initial gettimeofday() call added to usage clocks.
2619 // This can severely drift from time() and the microtime() value of other threads
2620 // due to undercounting of the amount of time elapsed. Instead of seeing the current
2621 // time as being in the past, use the value of time(). This avoids setting cache values
2622 // that will immediately be seen as expired and possibly cause stampedes.
2623 return max( microtime( true ), $clockTime );
2624 }
2625
2626 /**
2627 * @param float|null &$time Mock UNIX timestamp for testing
2628 * @codeCoverageIgnore
2629 */
2630 public function setMockTime( &$time ) {
2631 $this->wallClockOverride =& $time;
2632 $this->cache->setMockTime( $time );
2633 }
2634 }