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