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