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