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