Merge "objectcache: add setMockTime() method to BagOStuff/WANObjectCache"
[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 * All operations go to the local datacenter cache, except for delete(),
31 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
32 *
33 * This class is intended for caching data from primary stores.
34 * If the get() method does not return a value, then the caller
35 * should query the new value and backfill the cache using set().
36 * The preferred way to do this logic is through getWithSetCallback().
37 * When querying the store on cache miss, the closest DB replica
38 * should be used. Try to avoid heavyweight DB master or quorum reads.
39 * When the source data changes, a purge method should be called.
40 * Since purges are expensive, they should be avoided. One can do so if:
41 * - a) The object cached is immutable; or
42 * - b) Validity is checked against the source after get(); or
43 * - c) Using a modest TTL is reasonably correct and performant
44 *
45 * The simplest purge method is delete().
46 *
47 * There are three supported ways to handle broadcasted operations:
48 * - a) Configure the 'purge' EventRelayer to point to a valid PubSub endpoint
49 * that has subscribed listeners on the cache servers applying the cache updates.
50 * - b) Ommit the 'purge' EventRelayer parameter and set up mcrouter as the underlying cache
51 * backend, using a memcached BagOStuff class for the 'cache' parameter. The 'region'
52 * and 'cluster' parameters must be provided and 'mcrouterAware' must be set to 'true'.
53 * Configure mcrouter as follows:
54 * - 1) Use Route Prefixing based on region (datacenter) and cache cluster.
55 * See https://github.com/facebook/mcrouter/wiki/Routing-Prefix and
56 * https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
57 * - 2) To increase the consistency of delete() and touchCheckKey() during cache
58 * server membership changes, you can use the OperationSelectorRoute to
59 * configure 'set' and 'delete' operations to go to all servers in the cache
60 * cluster, instead of just one server determined by hashing.
61 * See https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles
62 * - c) Ommit the 'purge' EventRelayer parameter and set up dynomite as cache middleware
63 * between the web servers and either memcached or redis. This will also broadcast all
64 * key setting operations, not just purges, which can be useful for cache warming.
65 * Writes are eventually consistent via the Dynamo replication model.
66 * See https://github.com/Netflix/dynomite
67 *
68 * Broadcasted operations like delete() and touchCheckKey() are done asynchronously
69 * in all datacenters this way, though the local one should likely be near immediate.
70 *
71 * This means that callers in all datacenters may see older values for however many
72 * milliseconds that the purge took to reach that datacenter. As with any cache, this
73 * should not be relied on for cases where reads are used to determine writes to source
74 * (e.g. non-cache) data stores, except when reading immutable data.
75 *
76 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
77 * to avoid collisions with keys that are not wrapped as metadata arrays. The
78 * prefixes are as follows:
79 * - a) "WANCache:v" : used for regular value keys
80 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
81 * - c) "WANCache:t" : used for storing timestamp "check" keys
82 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
83 *
84 * @ingroup Cache
85 * @since 1.26
86 */
87 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
88 /** @var BagOStuff The local datacenter cache */
89 protected $cache;
90 /** @var HashBagOStuff[] Map of group PHP instance caches */
91 protected $processCaches = [];
92 /** @var string Purge channel name */
93 protected $purgeChannel;
94 /** @var EventRelayer Bus that handles purge broadcasts */
95 protected $purgeRelayer;
96 /** @bar bool Whether to use mcrouter key prefixing for routing */
97 protected $mcrouterAware;
98 /** @var string Physical region for mcrouter use */
99 protected $region;
100 /** @var string Cache cluster name for mcrouter use */
101 protected $cluster;
102 /** @var LoggerInterface */
103 protected $logger;
104 /** @var StatsdDataFactoryInterface */
105 protected $stats;
106 /** @var bool Whether to use "interim" caching while keys are tombstoned */
107 protected $useInterimHoldOffCaching = true;
108 /** @var callable|null Function that takes a WAN cache callback and runs it later */
109 protected $asyncHandler;
110
111 /** @var int ERR_* constant for the "last error" registry */
112 protected $lastRelayError = self::ERR_NONE;
113
114 /** @var int Callback stack depth for getWithSetCallback() */
115 private $callbackDepth = 0;
116 /** @var mixed[] Temporary warm-up cache */
117 private $warmupCache = [];
118 /** @var int Key fetched */
119 private $warmupKeyMisses = 0;
120
121 /** @var float|null */
122 private $wallClockOverride;
123
124 /** Max time expected to pass between delete() and DB commit finishing */
125 const MAX_COMMIT_DELAY = 3;
126 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
127 const MAX_READ_LAG = 7;
128 /** Seconds to tombstone keys on delete() */
129 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
130
131 /** Seconds to keep dependency purge keys around */
132 const CHECK_KEY_TTL = self::TTL_YEAR;
133 /** Seconds to keep interim value keys for tombstoned keys around */
134 const INTERIM_KEY_TTL = 1;
135
136 /** Seconds to keep lock keys around */
137 const LOCK_TTL = 10;
138 /** Default remaining TTL at which to consider pre-emptive regeneration */
139 const LOW_TTL = 30;
140
141 /** Never consider performing "popularity" refreshes until a key reaches this age */
142 const AGE_NEW = 60;
143 /** The time length of the "popularity" refresh window for hot keys */
144 const HOT_TTR = 900;
145 /** Hits/second for a refresh to be expected within the "popularity" window */
146 const HIT_RATE_HIGH = 1;
147 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
148 const RAMPUP_TTL = 30;
149
150 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
151 const TTL_UNCACHEABLE = -1;
152 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
153 const TSE_NONE = -1;
154 /** Max TTL to store keys when a data sourced is lagged */
155 const TTL_LAGGED = 30;
156 /** Idiom for delete() for "no hold-off" */
157 const HOLDOFF_NONE = 0;
158 /** Idiom for set()/getWithSetCallback() for "do not augment the storage medium TTL" */
159 const STALE_TTL_NONE = 0;
160 /** Idiom for set()/getWithSetCallback() for "no post-expired grace period" */
161 const GRACE_TTL_NONE = 0;
162
163 /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
164 const MIN_TIMESTAMP_NONE = 0.0;
165
166 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
167 const TINY_NEGATIVE = -0.000001;
168
169 /** Cache format version number */
170 const VERSION = 1;
171
172 const FLD_VERSION = 0; // key to cache version number
173 const FLD_VALUE = 1; // key to the cached value
174 const FLD_TTL = 2; // key to the original TTL
175 const FLD_TIME = 3; // key to the cache time
176 const FLD_FLAGS = 4; // key to the flags bitfield
177 const FLD_HOLDOFF = 5; // key to any hold-off TTL
178
179 /** @var int Treat this value as expired-on-arrival */
180 const FLG_STALE = 1;
181
182 const ERR_NONE = 0; // no error
183 const ERR_NO_RESPONSE = 1; // no response
184 const ERR_UNREACHABLE = 2; // can't connect
185 const ERR_UNEXPECTED = 3; // response gave some error
186 const ERR_RELAY = 4; // relay broadcast failed
187
188 const VALUE_KEY_PREFIX = 'WANCache:v:';
189 const INTERIM_KEY_PREFIX = 'WANCache:i:';
190 const TIME_KEY_PREFIX = 'WANCache:t:';
191 const MUTEX_KEY_PREFIX = 'WANCache:m:';
192
193 const PURGE_VAL_PREFIX = 'PURGED:';
194
195 const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
196 const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
197
198 const PC_PRIMARY = 'primary:1000'; // process cache name and max key count
199
200 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
201
202 /**
203 * @param array $params
204 * - cache : BagOStuff object for a persistent cache
205 * - channels : Map of (action => channel string). Actions include "purge".
206 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
207 * - logger : LoggerInterface object
208 * - stats : LoggerInterface object
209 * - asyncHandler : A function that takes a callback and runs it later. If supplied,
210 * whenever a preemptive refresh would be triggered in getWithSetCallback(), the
211 * current cache value is still used instead. However, the async-handler function
212 * receives a WAN cache callback that, when run, will execute the value generation
213 * callback supplied by the getWithSetCallback() caller. The result will be saved
214 * as normal. The handler is expected to call the WAN cache callback at an opportune
215 * time (e.g. HTTP post-send), though generally within a few 100ms. [optional]
216 * - region: the current physical region. This is required when using mcrouter as the
217 * backing store proxy. [optional]
218 * - cluster: name of the cache cluster used by this WAN cache. The name must be the
219 * same in all datacenters; the ("region","cluster") tuple is what distinguishes
220 * the counterpart cache clusters among all the datacenter. The contents of
221 * https://github.com/facebook/mcrouter/wiki/Config-Files give background on this.
222 * This is required when using mcrouter as the backing store proxy. [optional]
223 * - mcrouterAware: set as true if mcrouter is the backing store proxy and mcrouter
224 * is configured to interpret /<region>/<cluster>/ key prefixes as routes. This
225 * requires that "region" and "cluster" are both set above. [optional]
226 */
227 public function __construct( array $params ) {
228 $this->cache = $params['cache'];
229 $this->purgeChannel = $params['channels']['purge'] ?? self::DEFAULT_PURGE_CHANNEL;
230 $this->purgeRelayer = $params['relayers']['purge'] ?? new EventRelayerNull( [] );
231 $this->region = $params['region'] ?? 'main';
232 $this->cluster = $params['cluster'] ?? 'wan-main';
233 $this->mcrouterAware = !empty( $params['mcrouterAware'] );
234
235 $this->setLogger( $params['logger'] ?? new NullLogger() );
236 $this->stats = $params['stats'] ?? new NullStatsdDataFactory();
237 $this->asyncHandler = $params['asyncHandler'] ?? null;
238 }
239
240 /**
241 * @param LoggerInterface $logger
242 */
243 public function setLogger( LoggerInterface $logger ) {
244 $this->logger = $logger;
245 }
246
247 /**
248 * Get an instance that wraps EmptyBagOStuff
249 *
250 * @return WANObjectCache
251 */
252 public static function newEmpty() {
253 return new static( [
254 'cache' => new EmptyBagOStuff()
255 ] );
256 }
257
258 /**
259 * Fetch the value of a key from cache
260 *
261 * If supplied, $curTTL is set to the remaining TTL (current time left):
262 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
263 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
264 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
265 * - d) null; if $key does not exist and is not tombstoned
266 *
267 * If a key is tombstoned, $curTTL will reflect the time since delete().
268 *
269 * The timestamp of $key will be checked against the last-purge timestamp
270 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
271 * initialized to the current timestamp. If any of $checkKeys have a timestamp
272 * greater than that of $key, then $curTTL will reflect how long ago $key
273 * became invalid. Callers can use $curTTL to know when the value is stale.
274 * The $checkKeys parameter allow mass invalidations by updating a single key:
275 * - a) Each "check" key represents "last purged" of some source data
276 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
277 * - c) When the source data that "check" keys represent changes,
278 * the touchCheckKey() method is called on them
279 *
280 * Source data entities might exists in a DB that uses snapshot isolation
281 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
282 * isolation can largely be maintained by doing the following:
283 * - a) Calling delete() on entity change *and* creation, before DB commit
284 * - b) Keeping transaction duration shorter than the delete() hold-off TTL
285 * - c) Disabling interim key caching via useInterimHoldOffCaching() before get() calls
286 *
287 * However, pre-snapshot values might still be seen if an update was made
288 * in a remote datacenter but the purge from delete() didn't relay yet.
289 *
290 * Consider using getWithSetCallback() instead of get() and set() cycles.
291 * That method has cache slam avoiding features for hot/expensive keys.
292 *
293 * @param string $key Cache key made from makeKey() or makeGlobalKey()
294 * @param mixed &$curTTL Approximate TTL left on the key if present/tombstoned [returned]
295 * @param array $checkKeys List of "check" keys
296 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
297 * @return mixed Value of cache key or false on failure
298 */
299 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
300 $curTTLs = [];
301 $asOfs = [];
302 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
303 $curTTL = $curTTLs[$key] ?? null;
304 $asOf = $asOfs[$key] ?? null;
305
306 return $values[$key] ?? false;
307 }
308
309 /**
310 * Fetch the value of several keys from cache
311 *
312 * @see WANObjectCache::get()
313 *
314 * @param array $keys List of cache keys made from makeKey() or makeGlobalKey()
315 * @param array &$curTTLs Map of (key => approximate TTL left) for existing keys [returned]
316 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
317 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
318 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
319 * @return array Map of (key => value) for keys that exist and are not tombstoned
320 */
321 final public function getMulti(
322 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
323 ) {
324 $result = [];
325 $curTTLs = [];
326 $asOfs = [];
327
328 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
329 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
330
331 $checkKeysForAll = [];
332 $checkKeysByKey = [];
333 $checkKeysFlat = [];
334 foreach ( $checkKeys as $i => $checkKeyGroup ) {
335 $prefixed = self::prefixCacheKeys( (array)$checkKeyGroup, self::TIME_KEY_PREFIX );
336 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
337 // Is this check keys for a specific cache key, or for all keys being fetched?
338 if ( is_int( $i ) ) {
339 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
340 } else {
341 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
342 ? array_merge( $checkKeysByKey[$i], $prefixed )
343 : $prefixed;
344 }
345 }
346
347 // Fetch all of the raw values
348 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
349 if ( $this->warmupCache ) {
350 $wrappedValues = array_intersect_key( $this->warmupCache, array_flip( $keysGet ) );
351 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) ); // keys left to fetch
352 $this->warmupKeyMisses += count( $keysGet );
353 } else {
354 $wrappedValues = [];
355 }
356 if ( $keysGet ) {
357 $wrappedValues += $this->cache->getMulti( $keysGet );
358 }
359 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
360 $now = $this->getCurrentTime();
361
362 // Collect timestamps from all "check" keys
363 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
364 $purgeValuesByKey = [];
365 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
366 $purgeValuesByKey[$cacheKey] =
367 $this->processCheckKeys( $checks, $wrappedValues, $now );
368 }
369
370 // Get the main cache value for each key and validate them
371 foreach ( $valueKeys as $vKey ) {
372 if ( !isset( $wrappedValues[$vKey] ) ) {
373 continue; // not found
374 }
375
376 $key = substr( $vKey, $vPrefixLen ); // unprefix
377
378 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
379 if ( $value !== false ) {
380 $result[$key] = $value;
381
382 // Force dependant keys to be invalid for a while after purging
383 // to reduce race conditions involving stale data getting cached
384 $purgeValues = $purgeValuesForAll;
385 if ( isset( $purgeValuesByKey[$key] ) ) {
386 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
387 }
388 foreach ( $purgeValues as $purge ) {
389 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
390 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
391 // How long ago this value was expired by *this* check key
392 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
393 // How long ago this value was expired by *any* known check key
394 $curTTL = min( $curTTL, $ago );
395 }
396 }
397 }
398 $curTTLs[$key] = $curTTL;
399 $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
400 }
401
402 return $result;
403 }
404
405 /**
406 * @since 1.27
407 * @param array $timeKeys List of prefixed time check keys
408 * @param array $wrappedValues
409 * @param float $now
410 * @return array List of purge value arrays
411 */
412 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
413 $purgeValues = [];
414 foreach ( $timeKeys as $timeKey ) {
415 $purge = isset( $wrappedValues[$timeKey] )
416 ? $this->parsePurgeValue( $wrappedValues[$timeKey] )
417 : false;
418 if ( $purge === false ) {
419 // Key is not set or invalid; regenerate
420 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
421 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
422 $purge = $this->parsePurgeValue( $newVal );
423 }
424 $purgeValues[] = $purge;
425 }
426 return $purgeValues;
427 }
428
429 /**
430 * Set the value of a key in cache
431 *
432 * Simply calling this method when source data changes is not valid because
433 * the changes do not replicate to the other WAN sites. In that case, delete()
434 * should be used instead. This method is intended for use on cache misses.
435 *
436 * If the data was read from a snapshot-isolated transactions (e.g. the default
437 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
438 * - a) T1 starts
439 * - b) T2 updates a row, calls delete(), and commits
440 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
441 * - d) T1 reads the row and calls set() due to a cache miss
442 * - e) Stale value is stuck in cache
443 *
444 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
445 *
446 * Be aware that this does not update the process cache for getWithSetCallback()
447 * callers. Keys accessed via that method are not generally meant to also be set
448 * using this primitive method.
449 *
450 * Do not use this method on versioned keys accessed via getWithSetCallback().
451 *
452 * Example usage:
453 * @code
454 * $dbr = wfGetDB( DB_REPLICA );
455 * $setOpts = Database::getCacheSetOptions( $dbr );
456 * // Fetch the row from the DB
457 * $row = $dbr->selectRow( ... );
458 * $key = $cache->makeKey( 'building', $buildingId );
459 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
460 * @endcode
461 *
462 * @param string $key Cache key
463 * @param mixed $value
464 * @param int $ttl Seconds to live. Special values are:
465 * - WANObjectCache::TTL_INDEFINITE: Cache forever
466 * @param array $opts Options map:
467 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
468 * before the data was read or, if applicable, the replica DB lag before
469 * the snapshot-isolated transaction the data was read from started.
470 * Use false to indicate that replication is not running.
471 * Default: 0 seconds
472 * - since : UNIX timestamp of the data in $value. Typically, this is either
473 * the current time the data was read or (if applicable) the time when
474 * the snapshot-isolated transaction the data was read from started.
475 * Default: 0 seconds
476 * - pending : Whether this data is possibly from an uncommitted write transaction.
477 * Generally, other threads should not see values from the future and
478 * they certainly should not see ones that ended up getting rolled back.
479 * Default: false
480 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
481 * with this TTL and flag it as stale. This is only useful if the reads for this key
482 * use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set
483 * then it will still add on to this TTL in the excessive lag scenario.
484 * Default: WANObjectCache::TSE_NONE
485 * - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
486 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
487 * will call the regeneration callback in such cases, passing in the old value
488 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
489 * on the old value's as-of time when it is verified as still being correct.
490 * Default: WANObjectCache::STALE_TTL_NONE.
491 * @note Options added in 1.28: staleTTL
492 * @return bool Success
493 */
494 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
495 $now = $this->getCurrentTime();
496 $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
497 $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
498 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
499 $lag = $opts['lag'] ?? 0;
500
501 // Do not cache potentially uncommitted data as it might get rolled back
502 if ( !empty( $opts['pending'] ) ) {
503 $this->logger->info( 'Rejected set() for {cachekey} due to pending writes.',
504 [ 'cachekey' => $key ] );
505
506 return true; // no-op the write for being unsafe
507 }
508
509 $wrapExtra = []; // additional wrapped value fields
510 // Check if there's a risk of writing stale data after the purge tombstone expired
511 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
512 // Case A: read lag with "lockTSE"; save but record value as stale
513 if ( $lockTSE >= 0 ) {
514 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
515 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
516 // Case B: any long-running transaction; ignore this set()
517 } elseif ( $age > self::MAX_READ_LAG ) {
518 $this->logger->info( 'Rejected set() for {cachekey} due to snapshot lag.',
519 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] );
520
521 return true; // no-op the write for being unsafe
522 // Case C: high replication lag; lower TTL instead of ignoring all set()s
523 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
524 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
525 $this->logger->warning( 'Lowered set() TTL for {cachekey} due to replication lag.',
526 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] );
527 // Case D: medium length request with medium replication lag; ignore this set()
528 } else {
529 $this->logger->info( 'Rejected set() for {cachekey} due to high read lag.',
530 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ] );
531
532 return true; // no-op the write for being unsafe
533 }
534 }
535
536 // Wrap that value with time/TTL/version metadata
537 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
538
539 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
540 return ( is_string( $cWrapped ) )
541 ? false // key is tombstoned; do nothing
542 : $wrapped;
543 };
544
545 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl + $staleTTL, 1 );
546 }
547
548 /**
549 * Purge a key from all datacenters
550 *
551 * This should only be called when the underlying data (being cached)
552 * changes in a significant way. This deletes the key and starts a hold-off
553 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
554 * This is done to avoid the following race condition:
555 * - a) Some DB data changes and delete() is called on a corresponding key
556 * - b) A request refills the key with a stale value from a lagged DB
557 * - c) The stale value is stuck there until the key is expired/evicted
558 *
559 * This is implemented by storing a special "tombstone" value at the cache
560 * key that this class recognizes; get() calls will return false for the key
561 * and any set() calls will refuse to replace tombstone values at the key.
562 * For this to always avoid stale value writes, the following must hold:
563 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
564 * - b) If lag is higher, the DB will have gone into read-only mode already
565 *
566 * Note that set() can also be lag-aware and lower the TTL if it's high.
567 *
568 * Be aware that this does not clear the process cache. Even if it did, callbacks
569 * used by getWithSetCallback() might still return stale data in the case of either
570 * uncommitted or not-yet-replicated changes (callback generally use replica DBs).
571 *
572 * When using potentially long-running ACID transactions, a good pattern is
573 * to use a pre-commit hook to issue the delete. This means that immediately
574 * after commit, callers will see the tombstone in cache upon purge relay.
575 * It also avoids the following race condition:
576 * - a) T1 begins, changes a row, and calls delete()
577 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
578 * - c) T2 starts, reads the row and calls set() due to a cache miss
579 * - d) T1 finally commits
580 * - e) Stale value is stuck in cache
581 *
582 * Example usage:
583 * @code
584 * $dbw->startAtomic( __METHOD__ ); // start of request
585 * ... <execute some stuff> ...
586 * // Update the row in the DB
587 * $dbw->update( ... );
588 * $key = $cache->makeKey( 'homes', $homeId );
589 * // Purge the corresponding cache entry just before committing
590 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
591 * $cache->delete( $key );
592 * } );
593 * ... <execute some stuff> ...
594 * $dbw->endAtomic( __METHOD__ ); // end of request
595 * @endcode
596 *
597 * The $ttl parameter can be used when purging values that have not actually changed
598 * recently. For example, a cleanup script to purge cache entries does not really need
599 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
600 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
601 *
602 * If called twice on the same key, then the last hold-off TTL takes precedence. For
603 * idempotence, the $ttl should not vary for different delete() calls on the same key.
604 *
605 * @param string $key Cache key
606 * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
607 * @return bool True if the item was purged or not found, false on failure
608 */
609 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
610 $key = self::VALUE_KEY_PREFIX . $key;
611
612 if ( $ttl <= 0 ) {
613 // Publish the purge to all datacenters
614 $ok = $this->relayDelete( $key );
615 } else {
616 // Publish the purge to all datacenters
617 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE );
618 }
619
620 return $ok;
621 }
622
623 /**
624 * Fetch the value of a timestamp "check" key
625 *
626 * The key will be *initialized* to the current time if not set,
627 * so only call this method if this behavior is actually desired
628 *
629 * The timestamp can be used to check whether a cached value is valid.
630 * Callers should not assume that this returns the same timestamp in
631 * all datacenters due to relay delays.
632 *
633 * The level of staleness can roughly be estimated from this key, but
634 * if the key was evicted from cache, such calculations may show the
635 * time since expiry as ~0 seconds.
636 *
637 * Note that "check" keys won't collide with other regular keys.
638 *
639 * @param string $key
640 * @return float UNIX timestamp
641 */
642 final public function getCheckKeyTime( $key ) {
643 return $this->getMultiCheckKeyTime( [ $key ] )[$key];
644 }
645
646 /**
647 * Fetch the values of each timestamp "check" key
648 *
649 * This works like getCheckKeyTime() except it takes a list of keys
650 * and returns a map of timestamps instead of just that of one key
651 *
652 * This might be useful if both:
653 * - a) a class of entities each depend on hundreds of other entities
654 * - b) these other entities are depended upon by millions of entities
655 *
656 * The later entities can each use a "check" key to invalidate their dependee entities.
657 * However, it is expensive for the former entities to verify against all of the relevant
658 * "check" keys during each getWithSetCallback() call. A less expensive approach is to do
659 * these verifications only after a "time-till-verify" (TTV) has passed. This is a middle
660 * ground between using blind TTLs and using constant verification. The adaptiveTTL() method
661 * can be used to dynamically adjust the TTV. Also, the initial TTV can make use of the
662 * last-modified times of the dependant entities (either from the DB or the "check" keys).
663 *
664 * Example usage:
665 * @code
666 * $value = $cache->getWithSetCallback(
667 * $cache->makeGlobalKey( 'wikibase-item', $id ),
668 * self::INITIAL_TTV, // initial time-till-verify
669 * function ( $oldValue, &$ttv, &$setOpts, $oldAsOf ) use ( $checkKeys, $cache ) {
670 * $now = microtime( true );
671 * // Use $oldValue if it passes max ultimate age and "check" key comparisons
672 * if ( $oldValue &&
673 * $oldAsOf > max( $cache->getMultiCheckKeyTime( $checkKeys ) ) &&
674 * ( $now - $oldValue['ctime'] ) <= self::MAX_CACHE_AGE
675 * ) {
676 * // Increase time-till-verify by 50% of last time to reduce overhead
677 * $ttv = $cache->adaptiveTTL( $oldAsOf, self::MAX_TTV, self::MIN_TTV, 1.5 );
678 * // Unlike $oldAsOf, "ctime" is the ultimate age of the cached data
679 * return $oldValue;
680 * }
681 *
682 * $mtimes = []; // dependency last-modified times; passed by reference
683 * $value = [ 'data' => $this->fetchEntityData( $mtimes ), 'ctime' => $now ];
684 * // Guess time-till-change among the dependencies, e.g. 1/(total change rate)
685 * $ttc = 1 / array_sum( array_map(
686 * function ( $mtime ) use ( $now ) {
687 * return 1 / ( $mtime ? ( $now - $mtime ) : 900 );
688 * },
689 * $mtimes
690 * ) );
691 * // The time-to-verify should not be overly pessimistic nor optimistic
692 * $ttv = min( max( $ttc, self::MIN_TTV ), self::MAX_TTV );
693 *
694 * return $value;
695 * },
696 * [ 'staleTTL' => $cache::TTL_DAY ] // keep around to verify and re-save
697 * );
698 * @endcode
699 *
700 * @see WANObjectCache::getCheckKeyTime()
701 * @see WANObjectCache::getWithSetCallback()
702 *
703 * @param array $keys
704 * @return float[] Map of (key => UNIX timestamp)
705 * @since 1.31
706 */
707 final public function getMultiCheckKeyTime( array $keys ) {
708 $rawKeys = [];
709 foreach ( $keys as $key ) {
710 $rawKeys[$key] = self::TIME_KEY_PREFIX . $key;
711 }
712
713 $rawValues = $this->cache->getMulti( $rawKeys );
714 $rawValues += array_fill_keys( $rawKeys, false );
715
716 $times = [];
717 foreach ( $rawKeys as $key => $rawKey ) {
718 $purge = $this->parsePurgeValue( $rawValues[$rawKey] );
719 if ( $purge !== false ) {
720 $time = $purge[self::FLD_TIME];
721 } else {
722 // Casting assures identical floats for the next getCheckKeyTime() calls
723 $now = (string)$this->getCurrentTime();
724 $this->cache->add(
725 $rawKey,
726 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
727 self::CHECK_KEY_TTL
728 );
729 $time = (float)$now;
730 }
731
732 $times[$key] = $time;
733 }
734
735 return $times;
736 }
737
738 /**
739 * Purge a "check" key from all datacenters, invalidating keys that use it
740 *
741 * This should only be called when the underlying data (being cached)
742 * changes in a significant way, and it is impractical to call delete()
743 * on all keys that should be changed. When get() is called on those
744 * keys, the relevant "check" keys must be supplied for this to work.
745 *
746 * The "check" key essentially represents a last-modified time of an entity.
747 * When the key is touched, the timestamp will be updated to the current time.
748 * Keys using the "check" key via get(), getMulti(), or getWithSetCallback() will
749 * be invalidated. This approach is useful if many keys depend on a single entity.
750 *
751 * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the
752 * future by get*() methods in order to avoid race conditions where keys are updated
753 * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check"
754 * key, making it possible to know the timestamp of the last change to the corresponding
755 * entities in most cases. This might use more cache space than resetCheckKey().
756 *
757 * When a few important keys get a large number of hits, a high cache time is usually
758 * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate
759 * in such cases since the "time since expiry" cannot be inferred, causing any get()
760 * after the reset to treat the key as being "hot", resulting in more stale value usage.
761 *
762 * Note that "check" keys won't collide with other regular keys.
763 *
764 * @see WANObjectCache::get()
765 * @see WANObjectCache::getWithSetCallback()
766 * @see WANObjectCache::resetCheckKey()
767 *
768 * @param string $key Cache key
769 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
770 * @return bool True if the item was purged or not found, false on failure
771 */
772 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
773 // Publish the purge to all datacenters
774 return $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
775 }
776
777 /**
778 * Delete a "check" key from all datacenters, invalidating keys that use it
779 *
780 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
781 * or getWithSetCallback() will be invalidated. The differences are:
782 * - a) The "check" key will be deleted from all caches and lazily
783 * re-initialized when accessed (rather than set everywhere)
784 * - b) Thus, dependent keys will be known to be invalid, but not
785 * for how long (they are treated as "just" purged), which
786 * effects any lockTSE logic in getWithSetCallback()
787 * - c) Since "check" keys are initialized only on the server the key hashes
788 * to, any temporary ejection of that server will cause the value to be
789 * seen as purged as a new server will initialize the "check" key.
790 *
791 * The advantage here is that the "check" keys, which have high TTLs, will only
792 * be created when a get*() method actually uses that key. This is better when
793 * a large number of "check" keys are invalided in a short period of time.
794 *
795 * Note that "check" keys won't collide with other regular keys.
796 *
797 * @see WANObjectCache::get()
798 * @see WANObjectCache::getWithSetCallback()
799 * @see WANObjectCache::touchCheckKey()
800 *
801 * @param string $key Cache key
802 * @return bool True if the item was purged or not found, false on failure
803 */
804 final public function resetCheckKey( $key ) {
805 // Publish the purge to all datacenters
806 return $this->relayDelete( self::TIME_KEY_PREFIX . $key );
807 }
808
809 /**
810 * Method to fetch/regenerate cache keys
811 *
812 * On cache miss, the key will be set to the callback result via set()
813 * (unless the callback returns false) and that result will be returned.
814 * The arguments supplied to the callback are:
815 * - $oldValue : current cache value or false if not present
816 * - &$ttl : a reference to the TTL which can be altered
817 * - &$setOpts : a reference to options for set() which can be altered
818 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
819 *
820 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
821 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
822 * value, but it can be used to maintain "most recent X" values that come from time or
823 * sequence based source data, provided that the "as of" id/time is tracked. Note that
824 * preemptive regeneration and $checkKeys can result in a non-false current value.
825 *
826 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
827 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
828 * regeneration will automatically be triggered using the callback.
829 *
830 * The $ttl argument and "hotTTR" option (in $opts) use time-dependant randomization
831 * to avoid stampedes. Keys that are slow to regenerate and either heavily used
832 * or subject to explicit (unpredictable) purges, may need additional mechanisms.
833 * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts).
834 * If explicit purges are needed, also:
835 * - a) Pass $key into $checkKeys
836 * - b) Use touchCheckKey( $key ) instead of delete( $key )
837 *
838 * Example usage (typical key):
839 * @code
840 * $catInfo = $cache->getWithSetCallback(
841 * // Key to store the cached value under
842 * $cache->makeKey( 'cat-attributes', $catId ),
843 * // Time-to-live (in seconds)
844 * $cache::TTL_MINUTE,
845 * // Function that derives the new key value
846 * function ( $oldValue, &$ttl, array &$setOpts ) {
847 * $dbr = wfGetDB( DB_REPLICA );
848 * // Account for any snapshot/replica DB lag
849 * $setOpts += Database::getCacheSetOptions( $dbr );
850 *
851 * return $dbr->selectRow( ... );
852 * }
853 * );
854 * @endcode
855 *
856 * Example usage (key that is expensive and hot):
857 * @code
858 * $catConfig = $cache->getWithSetCallback(
859 * // Key to store the cached value under
860 * $cache->makeKey( 'site-cat-config' ),
861 * // Time-to-live (in seconds)
862 * $cache::TTL_DAY,
863 * // Function that derives the new key value
864 * function ( $oldValue, &$ttl, array &$setOpts ) {
865 * $dbr = wfGetDB( DB_REPLICA );
866 * // Account for any snapshot/replica DB lag
867 * $setOpts += Database::getCacheSetOptions( $dbr );
868 *
869 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
870 * },
871 * [
872 * // Calling touchCheckKey() on this key invalidates the cache
873 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
874 * // Try to only let one datacenter thread manage cache updates at a time
875 * 'lockTSE' => 30,
876 * // Avoid querying cache servers multiple times in a web request
877 * 'pcTTL' => $cache::TTL_PROC_LONG
878 * ]
879 * );
880 * @endcode
881 *
882 * Example usage (key with dynamic dependencies):
883 * @code
884 * $catState = $cache->getWithSetCallback(
885 * // Key to store the cached value under
886 * $cache->makeKey( 'cat-state', $cat->getId() ),
887 * // Time-to-live (seconds)
888 * $cache::TTL_HOUR,
889 * // Function that derives the new key value
890 * function ( $oldValue, &$ttl, array &$setOpts ) {
891 * // Determine new value from the DB
892 * $dbr = wfGetDB( DB_REPLICA );
893 * // Account for any snapshot/replica DB lag
894 * $setOpts += Database::getCacheSetOptions( $dbr );
895 *
896 * return CatState::newFromResults( $dbr->select( ... ) );
897 * },
898 * [
899 * // The "check" keys that represent things the value depends on;
900 * // Calling touchCheckKey() on any of them invalidates the cache
901 * 'checkKeys' => [
902 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
903 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
904 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
905 * ]
906 * ]
907 * );
908 * @endcode
909 *
910 * Example usage (hot key holding most recent 100 events):
911 * @code
912 * $lastCatActions = $cache->getWithSetCallback(
913 * // Key to store the cached value under
914 * $cache->makeKey( 'cat-last-actions', 100 ),
915 * // Time-to-live (in seconds)
916 * 10,
917 * // Function that derives the new key value
918 * function ( $oldValue, &$ttl, array &$setOpts ) {
919 * $dbr = wfGetDB( DB_REPLICA );
920 * // Account for any snapshot/replica DB lag
921 * $setOpts += Database::getCacheSetOptions( $dbr );
922 *
923 * // Start off with the last cached list
924 * $list = $oldValue ?: [];
925 * // Fetch the last 100 relevant rows in descending order;
926 * // only fetch rows newer than $list[0] to reduce scanning
927 * $rows = iterator_to_array( $dbr->select( ... ) );
928 * // Merge them and get the new "last 100" rows
929 * return array_slice( array_merge( $new, $list ), 0, 100 );
930 * },
931 * [
932 * // Try to only let one datacenter thread manage cache updates at a time
933 * 'lockTSE' => 30,
934 * // Use a magic value when no cache value is ready rather than stampeding
935 * 'busyValue' => 'computing'
936 * ]
937 * );
938 * @endcode
939 *
940 * Example usage (key holding an LRU subkey:value map; this can avoid flooding cache with
941 * keys for an unlimited set of (constraint,situation) pairs, thereby avoiding elevated
942 * cache evictions and wasted memory):
943 * @code
944 * $catSituationTolerabilityCache = $this->cache->getWithSetCallback(
945 * // Group by constraint ID/hash, cat family ID/hash, or something else useful
946 * $this->cache->makeKey( 'cat-situation-tolerablity-checks', $groupKey ),
947 * WANObjectCache::TTL_DAY, // rarely used groups should fade away
948 * // The $scenarioKey format is $constraintId:<ID/hash of $situation>
949 * function ( $cacheMap ) use ( $scenarioKey, $constraintId, $situation ) {
950 * $lruCache = MapCacheLRU::newFromArray( $cacheMap ?: [], self::CACHE_SIZE );
951 * $result = $lruCache->get( $scenarioKey ); // triggers LRU bump if present
952 * if ( $result === null || $this->isScenarioResultExpired( $result ) ) {
953 * $result = $this->checkScenarioTolerability( $constraintId, $situation );
954 * $lruCache->set( $scenarioKey, $result, 3 / 8 );
955 * }
956 * // Save the new LRU cache map and reset the map's TTL
957 * return $lruCache->toArray();
958 * },
959 * [
960 * // Once map is > 1 sec old, consider refreshing
961 * 'ageNew' => 1,
962 * // Update within 5 seconds after "ageNew" given a 1hz cache check rate
963 * 'hotTTR' => 5,
964 * // Avoid querying cache servers multiple times in a request; this also means
965 * // that a request can only alter the value of any given constraint key once
966 * 'pcTTL' => WANObjectCache::TTL_PROC_LONG
967 * ]
968 * );
969 * $tolerability = isset( $catSituationTolerabilityCache[$scenarioKey] )
970 * ? $catSituationTolerabilityCache[$scenarioKey]
971 * : $this->checkScenarioTolerability( $constraintId, $situation );
972 * @endcode
973 *
974 * @see WANObjectCache::get()
975 * @see WANObjectCache::set()
976 *
977 * @param string $key Cache key made from makeKey() or makeGlobalKey()
978 * @param int $ttl Seconds to live for key updates. Special values are:
979 * - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
980 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
981 * @param callable $callback Value generation function
982 * @param array $opts Options map:
983 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
984 * touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This
985 * is useful if thousands or millions of keys depend on the same entity. The entity can
986 * simply have its "check" key updated whenever the entity is modified.
987 * Default: [].
988 * - graceTTL: Consider reusing expired values instead of refreshing them if they expired
989 * less than this many seconds ago. The odds of a refresh becomes more likely over time,
990 * becoming certain once the grace period is reached. This can reduce traffic spikes
991 * when millions of keys are compared to the same "check" key and touchCheckKey()
992 * or resetCheckKey() is called on that "check" key.
993 * Default: WANObjectCache::GRACE_TTL_NONE.
994 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
995 * ago, then try to have a single thread handle cache regeneration at any given time.
996 * Other threads will try to use stale values if possible. If, on miss, the time since
997 * expiration is low, the assumption is that the key is hot and that a stampede is worth
998 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
999 * higher this is set, the higher the worst-case staleness can be.
1000 * Use WANObjectCache::TSE_NONE to disable this logic.
1001 * Default: WANObjectCache::TSE_NONE.
1002 * - busyValue: If no value exists and another thread is currently regenerating it, use this
1003 * as a fallback value (or a callback to generate such a value). This assures that cache
1004 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
1005 * against cache regeneration becoming very slow for some reason (greater than the TTL).
1006 * Default: null.
1007 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
1008 * network I/O when a key is read several times. This will not cache when the callback
1009 * returns false, however. Note that any purges will not be seen while process cached;
1010 * since the callback should use replica DBs and they may be lagged or have snapshot
1011 * isolation anyway, this should not typically matter.
1012 * Default: WANObjectCache::TTL_UNCACHEABLE.
1013 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
1014 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
1015 * large values, small yet numerous values, or some values with a high cost of eviction.
1016 * It is generally preferable to use a class constant when setting this value.
1017 * This has no effect unless pcTTL is used.
1018 * Default: WANObjectCache::PC_PRIMARY.
1019 * - version: Integer version number. This allows for callers to make breaking changes to
1020 * how values are stored while maintaining compatability and correct cache purges. New
1021 * versions are stored alongside older versions concurrently. Avoid storing class objects
1022 * however, as this reduces compatibility (due to serialization).
1023 * Default: null.
1024 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
1025 * This is useful if the source of a key is suspected of having possibly changed
1026 * recently, and the caller wants any such changes to be reflected.
1027 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
1028 * - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per
1029 * second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this
1030 * TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old.
1031 * This uses randomization to avoid triggering cache stampedes. The TTR is useful at
1032 * reducing the impact of missed cache purges, since the effect of a heavily referenced
1033 * key being stale is worse than that of a rarely referenced key. Unlike simply lowering
1034 * $ttl, seldomly used keys are largely unaffected by this option, which makes it
1035 * possible to have a high hit rate for the "long-tail" of less-used keys.
1036 * Default: WANObjectCache::HOT_TTR.
1037 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
1038 * than this. It becomes more likely over time, becoming certain once the key is expired.
1039 * This helps avoid cache stampedes that might be triggered due to the key expiring.
1040 * Default: WANObjectCache::LOW_TTL.
1041 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
1042 * Default: WANObjectCache::AGE_NEW.
1043 * - staleTTL: Seconds to keep the key around if it is stale. This means that on cache
1044 * miss the callback may get $oldValue/$oldAsOf values for keys that have already been
1045 * expired for this specified time. This is useful if adaptiveTTL() is used on the old
1046 * value's as-of time when it is verified as still being correct.
1047 * Default: WANObjectCache::STALE_TTL_NONE
1048 * @return mixed Value found or written to the key
1049 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
1050 * @note Options added in 1.31: staleTTL, graceTTL
1051 * @note Callable type hints are not used to avoid class-autoloading
1052 */
1053 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
1054 $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
1055
1056 // Try the process cache if enabled and the cache callback is not within a cache callback.
1057 // Process cache use in nested callbacks is not lag-safe with regard to HOLDOFF_TTL since
1058 // the in-memory value is further lagged than the shared one since it uses a blind TTL.
1059 if ( $pcTTL >= 0 && $this->callbackDepth == 0 ) {
1060 $group = $opts['pcGroup'] ?? self::PC_PRIMARY;
1061 $procCache = $this->getProcessCache( $group );
1062 $value = $procCache->get( $key );
1063 } else {
1064 $procCache = false;
1065 $value = false;
1066 }
1067
1068 if ( $value === false ) {
1069 // Fetch the value over the network
1070 if ( isset( $opts['version'] ) ) {
1071 $version = $opts['version'];
1072 $asOf = null;
1073 $cur = $this->doGetWithSetCallback(
1074 $key,
1075 $ttl,
1076 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1077 use ( $callback, $version ) {
1078 if ( is_array( $oldValue )
1079 && array_key_exists( self::VFLD_DATA, $oldValue )
1080 && array_key_exists( self::VFLD_VERSION, $oldValue )
1081 && $oldValue[self::VFLD_VERSION] === $version
1082 ) {
1083 $oldData = $oldValue[self::VFLD_DATA];
1084 } else {
1085 // VFLD_DATA is not set if an old, unversioned, key is present
1086 $oldData = false;
1087 $oldAsOf = null;
1088 }
1089
1090 return [
1091 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
1092 self::VFLD_VERSION => $version
1093 ];
1094 },
1095 $opts,
1096 $asOf
1097 );
1098 if ( $cur[self::VFLD_VERSION] === $version ) {
1099 // Value created or existed before with version; use it
1100 $value = $cur[self::VFLD_DATA];
1101 } else {
1102 // Value existed before with a different version; use variant key.
1103 // Reflect purges to $key by requiring that this key value be newer.
1104 $value = $this->doGetWithSetCallback(
1105 $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), $version ),
1106 $ttl,
1107 $callback,
1108 // Regenerate value if not newer than $key
1109 [ 'version' => null, 'minAsOf' => $asOf ] + $opts
1110 );
1111 }
1112 } else {
1113 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
1114 }
1115
1116 // Update the process cache if enabled
1117 if ( $procCache && $value !== false ) {
1118 $procCache->set( $key, $value, $pcTTL );
1119 }
1120 }
1121
1122 return $value;
1123 }
1124
1125 /**
1126 * Do the actual I/O for getWithSetCallback() when needed
1127 *
1128 * @see WANObjectCache::getWithSetCallback()
1129 *
1130 * @param string $key
1131 * @param int $ttl
1132 * @param callback $callback
1133 * @param array $opts Options map for getWithSetCallback()
1134 * @param float &$asOf Cache generation timestamp of returned value [returned]
1135 * @return mixed
1136 * @note Callable type hints are not used to avoid class-autoloading
1137 */
1138 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
1139 $lowTTL = $opts['lowTTL'] ?? min( self::LOW_TTL, $ttl );
1140 $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
1141 $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
1142 $graceTTL = $opts['graceTTL'] ?? self::GRACE_TTL_NONE;
1143 $checkKeys = $opts['checkKeys'] ?? [];
1144 $busyValue = $opts['busyValue'] ?? null;
1145 $popWindow = $opts['hotTTR'] ?? self::HOT_TTR;
1146 $ageNew = $opts['ageNew'] ?? self::AGE_NEW;
1147 $minTime = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
1148 $versioned = isset( $opts['version'] );
1149
1150 // Get a collection name to describe this class of key
1151 $kClass = $this->determineKeyClass( $key );
1152
1153 // Get the current key value
1154 $curTTL = null;
1155 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
1156 $value = $cValue; // return value
1157
1158 $preCallbackTime = $this->getCurrentTime();
1159 // Determine if a cached value regeneration is needed or desired
1160 if ( $value !== false
1161 && $this->isAliveOrInGracePeriod( $curTTL, $graceTTL )
1162 && $this->isValid( $value, $versioned, $asOf, $minTime )
1163 ) {
1164 $preemptiveRefresh = (
1165 $this->worthRefreshExpiring( $curTTL, $lowTTL ) ||
1166 $this->worthRefreshPopular( $asOf, $ageNew, $popWindow, $preCallbackTime )
1167 );
1168
1169 if ( !$preemptiveRefresh ) {
1170 $this->stats->increment( "wanobjectcache.$kClass.hit.good" );
1171
1172 return $value;
1173 } elseif ( $this->asyncHandler ) {
1174 // Update the cache value later, such during post-send of an HTTP request
1175 $func = $this->asyncHandler;
1176 $func( function () use ( $key, $ttl, $callback, $opts, $asOf ) {
1177 $opts['minAsOf'] = INF; // force a refresh
1178 $this->doGetWithSetCallback( $key, $ttl, $callback, $opts, $asOf );
1179 } );
1180 $this->stats->increment( "wanobjectcache.$kClass.hit.refresh" );
1181
1182 return $value;
1183 }
1184 }
1185
1186 // A deleted key with a negative TTL left must be tombstoned
1187 $isTombstone = ( $curTTL !== null && $value === false );
1188 if ( $isTombstone && $lockTSE <= 0 ) {
1189 // Use the INTERIM value for tombstoned keys to reduce regeneration load
1190 $lockTSE = self::INTERIM_KEY_TTL;
1191 }
1192 // Assume a key is hot if requested soon after invalidation
1193 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
1194 // Use the mutex if there is no value and a busy fallback is given
1195 $checkBusy = ( $busyValue !== null && $value === false );
1196 // Decide whether a single thread should handle regenerations.
1197 // This avoids stampedes when $checkKeys are bumped and when preemptive
1198 // renegerations take too long. It also reduces regenerations while $key
1199 // is tombstoned. This balances cache freshness with avoiding DB load.
1200 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
1201
1202 $lockAcquired = false;
1203 if ( $useMutex ) {
1204 // Acquire a datacenter-local non-blocking lock
1205 if ( $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
1206 // Lock acquired; this thread should update the key
1207 $lockAcquired = true;
1208 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1209 $this->stats->increment( "wanobjectcache.$kClass.hit.stale" );
1210 // If it cannot be acquired; then the stale value can be used
1211 return $value;
1212 } else {
1213 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
1214 // For hot keys, either another thread has the lock or the lock failed;
1215 // use the INTERIM value from the last thread that regenerated it.
1216 $value = $this->getInterimValue( $key, $versioned, $minTime, $asOf );
1217 if ( $value !== false ) {
1218 $this->stats->increment( "wanobjectcache.$kClass.hit.volatile" );
1219
1220 return $value;
1221 }
1222 // Use the busy fallback value if nothing else
1223 if ( $busyValue !== null ) {
1224 $this->stats->increment( "wanobjectcache.$kClass.miss.busy" );
1225
1226 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
1227 }
1228 }
1229 }
1230
1231 if ( !is_callable( $callback ) ) {
1232 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
1233 }
1234
1235 // Generate the new value from the callback...
1236 $setOpts = [];
1237 ++$this->callbackDepth;
1238 try {
1239 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
1240 } finally {
1241 --$this->callbackDepth;
1242 }
1243 $valueIsCacheable = ( $value !== false && $ttl >= 0 );
1244
1245 // When delete() is called, writes are write-holed by the tombstone,
1246 // so use a special INTERIM key to pass the new value around threads.
1247 if ( ( $isTombstone && $lockTSE > 0 ) && $valueIsCacheable ) {
1248 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
1249 $newAsOf = $this->getCurrentTime();
1250 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
1251 // Avoid using set() to avoid pointless mcrouter broadcasting
1252 $this->setInterimValue( $key, $wrapped, $tempTTL );
1253 }
1254
1255 if ( $valueIsCacheable ) {
1256 $setOpts['lockTSE'] = $lockTSE;
1257 $setOpts['staleTTL'] = $staleTTL;
1258 // Use best known "since" timestamp if not provided
1259 $setOpts += [ 'since' => $preCallbackTime ];
1260 // Update the cache; this will fail if the key is tombstoned
1261 $this->set( $key, $value, $ttl, $setOpts );
1262 }
1263
1264 if ( $lockAcquired ) {
1265 // Avoid using delete() to avoid pointless mcrouter broadcasting
1266 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, (int)$preCallbackTime - 60 );
1267 }
1268
1269 $this->stats->increment( "wanobjectcache.$kClass.miss.compute" );
1270
1271 return $value;
1272 }
1273
1274 /**
1275 * @param string $key
1276 * @param bool $versioned
1277 * @param float $minTime
1278 * @param mixed &$asOf
1279 * @return mixed
1280 */
1281 protected function getInterimValue( $key, $versioned, $minTime, &$asOf ) {
1282 if ( !$this->useInterimHoldOffCaching ) {
1283 return false; // disabled
1284 }
1285
1286 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
1287 list( $value ) = $this->unwrap( $wrapped, $this->getCurrentTime() );
1288 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1289 $asOf = $wrapped[self::FLD_TIME];
1290
1291 return $value;
1292 }
1293
1294 return false;
1295 }
1296
1297 /**
1298 * @param string $key
1299 * @param array $wrapped
1300 * @param int $tempTTL
1301 */
1302 protected function setInterimValue( $key, $wrapped, $tempTTL ) {
1303 $this->cache->merge(
1304 self::INTERIM_KEY_PREFIX . $key,
1305 function () use ( $wrapped ) {
1306 return $wrapped;
1307 },
1308 $tempTTL,
1309 1
1310 );
1311 }
1312
1313 /**
1314 * Method to fetch multiple cache keys at once with regeneration
1315 *
1316 * This works the same as getWithSetCallback() except:
1317 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1318 * - b) The $callback argument expects a callback taking the following arguments:
1319 * - $id: ID of an entity to query
1320 * - $oldValue : the prior cache value or false if none was present
1321 * - &$ttl : a reference to the new value TTL in seconds
1322 * - &$setOpts : a reference to options for set() which can be altered
1323 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present
1324 * Aside from the additional $id argument, the other arguments function the same
1325 * way they do in getWithSetCallback().
1326 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1327 *
1328 * @see WANObjectCache::getWithSetCallback()
1329 * @see WANObjectCache::getMultiWithUnionSetCallback()
1330 *
1331 * Example usage:
1332 * @code
1333 * $rows = $cache->getMultiWithSetCallback(
1334 * // Map of cache keys to entity IDs
1335 * $cache->makeMultiKeys(
1336 * $this->fileVersionIds(),
1337 * function ( $id, WANObjectCache $cache ) {
1338 * return $cache->makeKey( 'file-version', $id );
1339 * }
1340 * ),
1341 * // Time-to-live (in seconds)
1342 * $cache::TTL_DAY,
1343 * // Function that derives the new key value
1344 * function ( $id, $oldValue, &$ttl, array &$setOpts ) {
1345 * $dbr = wfGetDB( DB_REPLICA );
1346 * // Account for any snapshot/replica DB lag
1347 * $setOpts += Database::getCacheSetOptions( $dbr );
1348 *
1349 * // Load the row for this file
1350 * $queryInfo = File::getQueryInfo();
1351 * $row = $dbr->selectRow(
1352 * $queryInfo['tables'],
1353 * $queryInfo['fields'],
1354 * [ 'id' => $id ],
1355 * __METHOD__,
1356 * [],
1357 * $queryInfo['joins']
1358 * );
1359 *
1360 * return $row ? (array)$row : false;
1361 * },
1362 * [
1363 * // Process cache for 30 seconds
1364 * 'pcTTL' => 30,
1365 * // Use a dedicated 500 item cache (initialized on-the-fly)
1366 * 'pcGroup' => 'file-versions:500'
1367 * ]
1368 * );
1369 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1370 * @endcode
1371 *
1372 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1373 * @param int $ttl Seconds to live for key updates
1374 * @param callable $callback Callback the yields entity regeneration callbacks
1375 * @param array $opts Options map
1376 * @return array Map of (cache key => value) in the same order as $keyedIds
1377 * @since 1.28
1378 */
1379 final public function getMultiWithSetCallback(
1380 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1381 ) {
1382 $valueKeys = array_keys( $keyedIds->getArrayCopy() );
1383 $checkKeys = $opts['checkKeys'] ?? [];
1384
1385 // Load required keys into process cache in one go
1386 $this->warmupCache = $this->getRawKeysForWarmup(
1387 $this->getNonProcessCachedKeys( $valueKeys, $opts ),
1388 $checkKeys
1389 );
1390 $this->warmupKeyMisses = 0;
1391
1392 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1393 $id = null; // current entity ID
1394 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf ) use ( $callback, &$id ) {
1395 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1396 };
1397
1398 $values = [];
1399 foreach ( $keyedIds as $key => $id ) { // preserve order
1400 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1401 }
1402
1403 $this->warmupCache = [];
1404
1405 return $values;
1406 }
1407
1408 /**
1409 * Method to fetch/regenerate multiple cache keys at once
1410 *
1411 * This works the same as getWithSetCallback() except:
1412 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1413 * - b) The $callback argument expects a callback returning a map of (ID => new value)
1414 * for all entity IDs in $ids and it takes the following arguments:
1415 * - $ids: a list of entity IDs that require cache regeneration
1416 * - &$ttls: a reference to the (entity ID => new TTL) map
1417 * - &$setOpts: a reference to options for set() which can be altered
1418 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1419 * - d) The "lockTSE" and "busyValue" options are ignored
1420 *
1421 * @see WANObjectCache::getWithSetCallback()
1422 * @see WANObjectCache::getMultiWithSetCallback()
1423 *
1424 * Example usage:
1425 * @code
1426 * $rows = $cache->getMultiWithUnionSetCallback(
1427 * // Map of cache keys to entity IDs
1428 * $cache->makeMultiKeys(
1429 * $this->fileVersionIds(),
1430 * function ( $id, WANObjectCache $cache ) {
1431 * return $cache->makeKey( 'file-version', $id );
1432 * }
1433 * ),
1434 * // Time-to-live (in seconds)
1435 * $cache::TTL_DAY,
1436 * // Function that derives the new key value
1437 * function ( array $ids, array &$ttls, array &$setOpts ) {
1438 * $dbr = wfGetDB( DB_REPLICA );
1439 * // Account for any snapshot/replica DB lag
1440 * $setOpts += Database::getCacheSetOptions( $dbr );
1441 *
1442 * // Load the rows for these files
1443 * $rows = [];
1444 * $queryInfo = File::getQueryInfo();
1445 * $res = $dbr->select(
1446 * $queryInfo['tables'],
1447 * $queryInfo['fields'],
1448 * [ 'id' => $ids ],
1449 * __METHOD__,
1450 * [],
1451 * $queryInfo['joins']
1452 * );
1453 * foreach ( $res as $row ) {
1454 * $rows[$row->id] = $row;
1455 * $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
1456 * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
1457 * }
1458 *
1459 * return $rows;
1460 * },
1461 * ]
1462 * );
1463 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1464 * @endcode
1465 *
1466 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1467 * @param int $ttl Seconds to live for key updates
1468 * @param callable $callback Callback the yields entity regeneration callbacks
1469 * @param array $opts Options map
1470 * @return array Map of (cache key => value) in the same order as $keyedIds
1471 * @since 1.30
1472 */
1473 final public function getMultiWithUnionSetCallback(
1474 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1475 ) {
1476 $idsByValueKey = $keyedIds->getArrayCopy();
1477 $valueKeys = array_keys( $idsByValueKey );
1478 $checkKeys = $opts['checkKeys'] ?? [];
1479 unset( $opts['lockTSE'] ); // incompatible
1480 unset( $opts['busyValue'] ); // incompatible
1481
1482 // Load required keys into process cache in one go
1483 $keysGet = $this->getNonProcessCachedKeys( $valueKeys, $opts );
1484 $this->warmupCache = $this->getRawKeysForWarmup( $keysGet, $checkKeys );
1485 $this->warmupKeyMisses = 0;
1486
1487 // IDs of entities known to be in need of regeneration
1488 $idsRegen = [];
1489
1490 // Find out which keys are missing/deleted/stale
1491 $curTTLs = [];
1492 $asOfs = [];
1493 $curByKey = $this->getMulti( $keysGet, $curTTLs, $checkKeys, $asOfs );
1494 foreach ( $keysGet as $key ) {
1495 if ( !array_key_exists( $key, $curByKey ) || $curTTLs[$key] < 0 ) {
1496 $idsRegen[] = $idsByValueKey[$key];
1497 }
1498 }
1499
1500 // Run the callback to populate the regeneration value map for all required IDs
1501 $newSetOpts = [];
1502 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
1503 $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
1504
1505 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1506 $id = null; // current entity ID
1507 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1508 use ( $callback, &$id, $newValsById, $newTTLsById, $newSetOpts )
1509 {
1510 if ( array_key_exists( $id, $newValsById ) ) {
1511 // Value was already regerated as expected, so use the value in $newValsById
1512 $newValue = $newValsById[$id];
1513 $ttl = $newTTLsById[$id];
1514 $setOpts = $newSetOpts;
1515 } else {
1516 // Pre-emptive/popularity refresh and version mismatch cases are not detected
1517 // above and thus $newValsById has no entry. Run $callback on this single entity.
1518 $ttls = [ $id => $ttl ];
1519 $newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
1520 $ttl = $ttls[$id];
1521 }
1522
1523 return $newValue;
1524 };
1525
1526 // Run the cache-aside logic using warmupCache instead of persistent cache queries
1527 $values = [];
1528 foreach ( $idsByValueKey as $key => $id ) { // preserve order
1529 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1530 }
1531
1532 $this->warmupCache = [];
1533
1534 return $values;
1535 }
1536
1537 /**
1538 * Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1539 *
1540 * This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids
1541 * broadcasting in mcrouter setups and also avoids races with new tombstones.
1542 *
1543 * @param string $key Cache key
1544 * @param int $purgeTimestamp UNIX timestamp of purge
1545 * @param bool &$isStale Whether the key is stale
1546 * @return bool Success
1547 * @since 1.28
1548 */
1549 final public function reap( $key, $purgeTimestamp, &$isStale = false ) {
1550 $minAsOf = $purgeTimestamp + self::HOLDOFF_TTL;
1551 $wrapped = $this->cache->get( self::VALUE_KEY_PREFIX . $key );
1552 if ( is_array( $wrapped ) && $wrapped[self::FLD_TIME] < $minAsOf ) {
1553 $isStale = true;
1554 $this->logger->warning( "Reaping stale value key '$key'." );
1555 $ttlReap = self::HOLDOFF_TTL; // avoids races with tombstone creation
1556 $ok = $this->cache->changeTTL( self::VALUE_KEY_PREFIX . $key, $ttlReap );
1557 if ( !$ok ) {
1558 $this->logger->error( "Could not complete reap of key '$key'." );
1559 }
1560
1561 return $ok;
1562 }
1563
1564 $isStale = false;
1565
1566 return true;
1567 }
1568
1569 /**
1570 * Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1571 *
1572 * @param string $key Cache key
1573 * @param int $purgeTimestamp UNIX timestamp of purge
1574 * @param bool &$isStale Whether the key is stale
1575 * @return bool Success
1576 * @since 1.28
1577 */
1578 final public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
1579 $purge = $this->parsePurgeValue( $this->cache->get( self::TIME_KEY_PREFIX . $key ) );
1580 if ( $purge && $purge[self::FLD_TIME] < $purgeTimestamp ) {
1581 $isStale = true;
1582 $this->logger->warning( "Reaping stale check key '$key'." );
1583 $ok = $this->cache->changeTTL( self::TIME_KEY_PREFIX . $key, self::TTL_SECOND );
1584 if ( !$ok ) {
1585 $this->logger->error( "Could not complete reap of check key '$key'." );
1586 }
1587
1588 return $ok;
1589 }
1590
1591 $isStale = false;
1592
1593 return false;
1594 }
1595
1596 /**
1597 * @see BagOStuff::makeKey()
1598 * @param string $class Key class
1599 * @param string $component [optional] Key component (starting with a key collection name)
1600 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1601 * @since 1.27
1602 */
1603 public function makeKey( $class, $component = null ) {
1604 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1605 }
1606
1607 /**
1608 * @see BagOStuff::makeGlobalKey()
1609 * @param string $class Key class
1610 * @param string $component [optional] Key component (starting with a key collection name)
1611 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1612 * @since 1.27
1613 */
1614 public function makeGlobalKey( $class, $component = null ) {
1615 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1616 }
1617
1618 /**
1619 * @param array $entities List of entity IDs
1620 * @param callable $keyFunc Callback yielding a key from (entity ID, this WANObjectCache)
1621 * @return ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
1622 * @since 1.28
1623 */
1624 final public function makeMultiKeys( array $entities, callable $keyFunc ) {
1625 $map = [];
1626 foreach ( $entities as $entity ) {
1627 $map[$keyFunc( $entity, $this )] = $entity;
1628 }
1629
1630 return new ArrayIterator( $map );
1631 }
1632
1633 /**
1634 * Get the "last error" registered; clearLastError() should be called manually
1635 * @return int ERR_* class constant for the "last error" registry
1636 */
1637 final public function getLastError() {
1638 if ( $this->lastRelayError ) {
1639 // If the cache and the relayer failed, focus on the latter.
1640 // An update not making it to the relayer means it won't show up
1641 // in other DCs (nor will consistent re-hashing see up-to-date values).
1642 // On the other hand, if just the cache update failed, then it should
1643 // eventually be applied by the relayer.
1644 return $this->lastRelayError;
1645 }
1646
1647 $code = $this->cache->getLastError();
1648 switch ( $code ) {
1649 case BagOStuff::ERR_NONE:
1650 return self::ERR_NONE;
1651 case BagOStuff::ERR_NO_RESPONSE:
1652 return self::ERR_NO_RESPONSE;
1653 case BagOStuff::ERR_UNREACHABLE:
1654 return self::ERR_UNREACHABLE;
1655 default:
1656 return self::ERR_UNEXPECTED;
1657 }
1658 }
1659
1660 /**
1661 * Clear the "last error" registry
1662 */
1663 final public function clearLastError() {
1664 $this->cache->clearLastError();
1665 $this->lastRelayError = self::ERR_NONE;
1666 }
1667
1668 /**
1669 * Clear the in-process caches; useful for testing
1670 *
1671 * @since 1.27
1672 */
1673 public function clearProcessCache() {
1674 $this->processCaches = [];
1675 }
1676
1677 /**
1678 * Enable or disable the use of brief caching for tombstoned keys
1679 *
1680 * When a key is purged via delete(), there normally is a period where caching
1681 * is hold-off limited to an extremely short time. This method will disable that
1682 * caching, forcing the callback to run for any of:
1683 * - WANObjectCache::getWithSetCallback()
1684 * - WANObjectCache::getMultiWithSetCallback()
1685 * - WANObjectCache::getMultiWithUnionSetCallback()
1686 *
1687 * This is useful when both:
1688 * - a) the database used by the callback is known to be up-to-date enough
1689 * for some particular purpose (e.g. replica DB has applied transaction X)
1690 * - b) the caller needs to exploit that fact, and therefore needs to avoid the
1691 * use of inherently volatile and possibly stale interim keys
1692 *
1693 * @see WANObjectCache::delete()
1694 * @param bool $enabled Whether to enable interim caching
1695 * @since 1.31
1696 */
1697 final public function useInterimHoldOffCaching( $enabled ) {
1698 $this->useInterimHoldOffCaching = $enabled;
1699 }
1700
1701 /**
1702 * @param int $flag ATTR_* class constant
1703 * @return int QOS_* class constant
1704 * @since 1.28
1705 */
1706 public function getQoS( $flag ) {
1707 return $this->cache->getQoS( $flag );
1708 }
1709
1710 /**
1711 * Get a TTL that is higher for objects that have not changed recently
1712 *
1713 * This is useful for keys that get explicit purges and DB or purge relay
1714 * lag is a potential concern (especially how it interacts with CDN cache)
1715 *
1716 * Example usage:
1717 * @code
1718 * // Last-modified time of page
1719 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1720 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1721 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1722 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1723 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1724 * @endcode
1725 *
1726 * Another use case is when there are no applicable "last modified" fields in the DB,
1727 * and there are too many dependencies for explicit purges to be viable, and the rate of
1728 * change to relevant content is unstable, and it is highly valued to have the cached value
1729 * be as up-to-date as possible.
1730 *
1731 * Example usage:
1732 * @code
1733 * $query = "<some complex query>";
1734 * $idListFromComplexQuery = $cache->getWithSetCallback(
1735 * $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
1736 * GraphQueryClass::STARTING_TTL,
1737 * function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
1738 * $gdb = $this->getReplicaGraphDbConnection();
1739 * // Account for any snapshot/replica DB lag
1740 * $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
1741 *
1742 * $newList = iterator_to_array( $gdb->query( $query ) );
1743 * sort( $newList, SORT_NUMERIC ); // normalize
1744 *
1745 * $minTTL = GraphQueryClass::MIN_TTL;
1746 * $maxTTL = GraphQueryClass::MAX_TTL;
1747 * if ( $oldValue !== false ) {
1748 * // Note that $oldAsOf is the last time this callback ran
1749 * $ttl = ( $newList === $oldValue )
1750 * // No change: cache for 150% of the age of $oldValue
1751 * ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
1752 * // Changed: cache for 50% of the age of $oldValue
1753 * : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
1754 * }
1755 *
1756 * return $newList;
1757 * },
1758 * [
1759 * // Keep stale values around for doing comparisons for TTL calculations.
1760 * // High values improve long-tail keys hit-rates, though might waste space.
1761 * 'staleTTL' => GraphQueryClass::GRACE_TTL
1762 * ]
1763 * );
1764 * @endcode
1765 *
1766 * @param int|float $mtime UNIX timestamp
1767 * @param int $maxTTL Maximum TTL (seconds)
1768 * @param int $minTTL Minimum TTL (seconds); Default: 30
1769 * @param float $factor Value in the range (0,1); Default: .2
1770 * @return int Adaptive TTL
1771 * @since 1.28
1772 */
1773 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
1774 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
1775 $mtime = (int)$mtime; // handle fractional seconds and string integers
1776 }
1777
1778 if ( !is_int( $mtime ) || $mtime <= 0 ) {
1779 return $minTTL; // no last-modified time provided
1780 }
1781
1782 $age = $this->getCurrentTime() - $mtime;
1783
1784 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1785 }
1786
1787 /**
1788 * @return int Number of warmup key cache misses last round
1789 * @since 1.30
1790 */
1791 final public function getWarmupKeyMisses() {
1792 return $this->warmupKeyMisses;
1793 }
1794
1795 /**
1796 * Do the actual async bus purge of a key
1797 *
1798 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1799 *
1800 * @param string $key Cache key
1801 * @param int $ttl How long to keep the tombstone [seconds]
1802 * @param int $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1803 * @return bool Success
1804 */
1805 protected function relayPurge( $key, $ttl, $holdoff ) {
1806 if ( $this->mcrouterAware ) {
1807 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
1808 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
1809 $ok = $this->cache->set(
1810 "/*/{$this->cluster}/{$key}",
1811 $this->makePurgeValue( $this->getCurrentTime(), self::HOLDOFF_NONE ),
1812 $ttl
1813 );
1814 } elseif ( $this->purgeRelayer instanceof EventRelayerNull ) {
1815 // This handles the mcrouter and the single-DC case
1816 $ok = $this->cache->set(
1817 $key,
1818 $this->makePurgeValue( $this->getCurrentTime(), self::HOLDOFF_NONE ),
1819 $ttl
1820 );
1821 } else {
1822 $event = $this->cache->modifySimpleRelayEvent( [
1823 'cmd' => 'set',
1824 'key' => $key,
1825 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1826 'ttl' => max( $ttl, self::TTL_SECOND ),
1827 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1828 ] );
1829
1830 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1831 if ( !$ok ) {
1832 $this->lastRelayError = self::ERR_RELAY;
1833 }
1834 }
1835
1836 return $ok;
1837 }
1838
1839 /**
1840 * Do the actual async bus delete of a key
1841 *
1842 * @param string $key Cache key
1843 * @return bool Success
1844 */
1845 protected function relayDelete( $key ) {
1846 if ( $this->mcrouterAware ) {
1847 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
1848 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
1849 $ok = $this->cache->delete( "/*/{$this->cluster}/{$key}" );
1850 } elseif ( $this->purgeRelayer instanceof EventRelayerNull ) {
1851 // Some other proxy handles broadcasting or there is only one datacenter
1852 $ok = $this->cache->delete( $key );
1853 } else {
1854 $event = $this->cache->modifySimpleRelayEvent( [
1855 'cmd' => 'delete',
1856 'key' => $key,
1857 ] );
1858
1859 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1860 if ( !$ok ) {
1861 $this->lastRelayError = self::ERR_RELAY;
1862 }
1863 }
1864
1865 return $ok;
1866 }
1867
1868 /**
1869 * Check if a key is fresh or in the grace window and thus due for randomized reuse
1870 *
1871 * If $curTTL > 0 (e.g. not expired) this returns true. Otherwise, the chance of returning
1872 * true decrease steadily from 100% to 0% as the |$curTTL| moves from 0 to $graceTTL seconds.
1873 * This handles widely varying levels of cache access traffic.
1874 *
1875 * If $curTTL <= -$graceTTL (e.g. already expired), then this returns false.
1876 *
1877 * @param float $curTTL Approximate TTL left on the key if present
1878 * @param int $graceTTL Consider using stale values if $curTTL is greater than this
1879 * @return bool
1880 */
1881 protected function isAliveOrInGracePeriod( $curTTL, $graceTTL ) {
1882 if ( $curTTL > 0 ) {
1883 return true;
1884 } elseif ( $graceTTL <= 0 ) {
1885 return false;
1886 }
1887
1888 $ageStale = abs( $curTTL ); // seconds of staleness
1889 $curGTTL = ( $graceTTL - $ageStale ); // current grace-time-to-live
1890 if ( $curGTTL <= 0 ) {
1891 return false; // already out of grace period
1892 }
1893
1894 // Chance of using a stale value is the complement of the chance of refreshing it
1895 return !$this->worthRefreshExpiring( $curGTTL, $graceTTL );
1896 }
1897
1898 /**
1899 * Check if a key is nearing expiration and thus due for randomized regeneration
1900 *
1901 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance of returning true
1902 * increases steadily from 0% to 100% as the $curTTL moves from $lowTTL to 0 seconds.
1903 * This handles widely varying levels of cache access traffic.
1904 *
1905 * If $curTTL <= 0 (e.g. already expired), then this returns false.
1906 *
1907 * @param float $curTTL Approximate TTL left on the key if present
1908 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1909 * @return bool
1910 */
1911 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1912 if ( $lowTTL <= 0 ) {
1913 return false;
1914 } elseif ( $curTTL >= $lowTTL ) {
1915 return false;
1916 } elseif ( $curTTL <= 0 ) {
1917 return false;
1918 }
1919
1920 $chance = ( 1 - $curTTL / $lowTTL );
1921
1922 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1923 }
1924
1925 /**
1926 * Check if a key is due for randomized regeneration due to its popularity
1927 *
1928 * This is used so that popular keys can preemptively refresh themselves for higher
1929 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
1930 * in cache with their high nominal TTL. This means popular keys keep good consistency,
1931 * whether the data changes frequently or not, and long-tail keys get to stay in cache
1932 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
1933 *
1934 * @param float $asOf UNIX timestamp of the value
1935 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
1936 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
1937 * @param float $now The current UNIX timestamp
1938 * @return bool
1939 */
1940 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
1941 if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
1942 return false;
1943 }
1944
1945 $age = $now - $asOf;
1946 $timeOld = $age - $ageNew;
1947 if ( $timeOld <= 0 ) {
1948 return false;
1949 }
1950
1951 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
1952 // Note that the "expected # of refreshes" for the ramp-up time range is half of what it
1953 // would be if P(refresh) was at its full value during that time range.
1954 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
1955 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1956 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1957 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1958 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
1959
1960 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1961 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
1962
1963 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1964 }
1965
1966 /**
1967 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1968 *
1969 * @param array $value
1970 * @param bool $versioned
1971 * @param float $asOf The time $value was generated
1972 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1973 * @return bool
1974 */
1975 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1976 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1977 return false;
1978 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1979 return false;
1980 }
1981
1982 return true;
1983 }
1984
1985 /**
1986 * Do not use this method outside WANObjectCache
1987 *
1988 * @param mixed $value
1989 * @param int $ttl [0=forever]
1990 * @param float $now Unix Current timestamp just before calling set()
1991 * @return array
1992 */
1993 protected function wrap( $value, $ttl, $now ) {
1994 return [
1995 self::FLD_VERSION => self::VERSION,
1996 self::FLD_VALUE => $value,
1997 self::FLD_TTL => $ttl,
1998 self::FLD_TIME => $now
1999 ];
2000 }
2001
2002 /**
2003 * Do not use this method outside WANObjectCache
2004 *
2005 * @param array|string|bool $wrapped
2006 * @param float $now Unix Current timestamp (preferrably pre-query)
2007 * @return array (mixed; false if absent/tombstoned/invalid, current time left)
2008 */
2009 protected function unwrap( $wrapped, $now ) {
2010 // Check if the value is a tombstone
2011 $purge = $this->parsePurgeValue( $wrapped );
2012 if ( $purge !== false ) {
2013 // Purged values should always have a negative current $ttl
2014 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
2015 return [ false, $curTTL ];
2016 }
2017
2018 if ( !is_array( $wrapped ) // not found
2019 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
2020 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
2021 ) {
2022 return [ false, null ];
2023 }
2024
2025 $flags = $wrapped[self::FLD_FLAGS] ?? 0;
2026 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
2027 // Treat as expired, with the cache time as the expiration
2028 $age = $now - $wrapped[self::FLD_TIME];
2029 $curTTL = min( -$age, self::TINY_NEGATIVE );
2030 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
2031 // Get the approximate time left on the key
2032 $age = $now - $wrapped[self::FLD_TIME];
2033 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
2034 } else {
2035 // Key had no TTL, so the time left is unbounded
2036 $curTTL = INF;
2037 }
2038
2039 return [ $wrapped[self::FLD_VALUE], $curTTL ];
2040 }
2041
2042 /**
2043 * @param array $keys
2044 * @param string $prefix
2045 * @return string[]
2046 */
2047 protected static function prefixCacheKeys( array $keys, $prefix ) {
2048 $res = [];
2049 foreach ( $keys as $key ) {
2050 $res[] = $prefix . $key;
2051 }
2052
2053 return $res;
2054 }
2055
2056 /**
2057 * @param string $key String of the format <scope>:<class>[:<class or variable>]...
2058 * @return string
2059 */
2060 protected function determineKeyClass( $key ) {
2061 $parts = explode( ':', $key );
2062
2063 return $parts[1] ?? $parts[0]; // sanity
2064 }
2065
2066 /**
2067 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
2068 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
2069 * or false if value isn't a valid purge value
2070 */
2071 protected function parsePurgeValue( $value ) {
2072 if ( !is_string( $value ) ) {
2073 return false;
2074 }
2075 $segments = explode( ':', $value, 3 );
2076 if ( !isset( $segments[0] ) || !isset( $segments[1] )
2077 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
2078 ) {
2079 return false;
2080 }
2081 if ( !isset( $segments[2] ) ) {
2082 // Back-compat with old purge values without holdoff
2083 $segments[2] = self::HOLDOFF_TTL;
2084 }
2085 return [
2086 self::FLD_TIME => (float)$segments[1],
2087 self::FLD_HOLDOFF => (int)$segments[2],
2088 ];
2089 }
2090
2091 /**
2092 * @param float $timestamp
2093 * @param int $holdoff In seconds
2094 * @return string Wrapped purge value
2095 */
2096 protected function makePurgeValue( $timestamp, $holdoff ) {
2097 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
2098 }
2099
2100 /**
2101 * @param string $group
2102 * @return HashBagOStuff
2103 */
2104 protected function getProcessCache( $group ) {
2105 if ( !isset( $this->processCaches[$group] ) ) {
2106 list( , $n ) = explode( ':', $group );
2107 $this->processCaches[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
2108 }
2109
2110 return $this->processCaches[$group];
2111 }
2112
2113 /**
2114 * @param array $keys
2115 * @param array $opts
2116 * @return array List of keys
2117 */
2118 private function getNonProcessCachedKeys( array $keys, array $opts ) {
2119 $keysFound = [];
2120 if ( isset( $opts['pcTTL'] ) && $opts['pcTTL'] > 0 && $this->callbackDepth == 0 ) {
2121 $pcGroup = $opts['pcGroup'] ?? self::PC_PRIMARY;
2122 $procCache = $this->getProcessCache( $pcGroup );
2123 foreach ( $keys as $key ) {
2124 if ( $procCache->get( $key ) !== false ) {
2125 $keysFound[] = $key;
2126 }
2127 }
2128 }
2129
2130 return array_diff( $keys, $keysFound );
2131 }
2132
2133 /**
2134 * @param array $keys
2135 * @param array $checkKeys
2136 * @return array Map of (cache key => mixed)
2137 */
2138 private function getRawKeysForWarmup( array $keys, array $checkKeys ) {
2139 if ( !$keys ) {
2140 return [];
2141 }
2142
2143 $keysWarmUp = [];
2144 // Get all the value keys to fetch...
2145 foreach ( $keys as $key ) {
2146 $keysWarmUp[] = self::VALUE_KEY_PREFIX . $key;
2147 }
2148 // Get all the check keys to fetch...
2149 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
2150 if ( is_int( $i ) ) {
2151 // Single check key that applies to all value keys
2152 $keysWarmUp[] = self::TIME_KEY_PREFIX . $checkKeyOrKeys;
2153 } else {
2154 // List of check keys that apply to value key $i
2155 $keysWarmUp = array_merge(
2156 $keysWarmUp,
2157 self::prefixCacheKeys( $checkKeyOrKeys, self::TIME_KEY_PREFIX )
2158 );
2159 }
2160 }
2161
2162 $warmupCache = $this->cache->getMulti( $keysWarmUp );
2163 $warmupCache += array_fill_keys( $keysWarmUp, false );
2164
2165 return $warmupCache;
2166 }
2167
2168 /**
2169 * @return float UNIX timestamp
2170 * @codeCoverageIgnore
2171 */
2172 protected function getCurrentTime() {
2173 return $this->wallClockOverride ?: microtime( true );
2174 }
2175
2176 /**
2177 * @param float|null &$time Mock UNIX timestamp for testing
2178 * @codeCoverageIgnore
2179 */
2180 public function setMockTime( &$time ) {
2181 $this->wallClockOverride =& $time;
2182 $this->cache->setMockTime( $time );
2183 }
2184 }