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