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