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