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