Only store currently-existing categories in the categories table
[mediawiki.git] / includes / libs / objectcache / WANObjectCache.php
blobab702d57be87a7d7b2bb75648e05cdd331671867
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.
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.
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
18 * @file
19 * @ingroup Cache
20 * @author Aaron Schulz
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
27 /**
28 * Multi-datacenter aware caching interface
30 * All operations go to the local datacenter cache, except for delete(),
31 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
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 * When querying the store on cache miss, the closest DB replica
37 * should be used. Try to avoid heavyweight DB master or quorum reads.
38 * When the source data changes, a purge method should be called.
39 * Since purges are expensive, they should be avoided. One can do so if:
40 * - a) The object cached is immutable; or
41 * - b) Validity is checked against the source after get(); or
42 * - c) Using a modest TTL is reasonably correct and performant
44 * The simplest purge method is delete().
46 * Instances of this class must be configured to point to a valid
47 * PubSub endpoint, and there must be listeners on the cache servers
48 * that subscribe to the endpoint and update the caches.
50 * Broadcasted operations like delete() and touchCheckKey() are done
51 * synchronously in the local datacenter, but are relayed asynchronously.
52 * This means that callers in other datacenters will see older values
53 * for however many milliseconds the datacenters are apart. As with
54 * any cache, this should not be relied on for cases where reads are
55 * used to determine writes to source (e.g. non-cache) data stores.
57 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
58 * to avoid collisions with keys that are not wrapped as metadata arrays. The
59 * prefixes are as follows:
60 * - a) "WANCache:v" : used for regular value keys
61 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
62 * - c) "WANCache:t" : used for storing timestamp "check" keys
64 * @ingroup Cache
65 * @since 1.26
67 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
68 /** @var BagOStuff The local datacenter cache */
69 protected $cache;
70 /** @var HashBagOStuff Script instance PHP cache */
71 protected $procCache;
72 /** @var string Purge channel name */
73 protected $purgeChannel;
74 /** @var EventRelayer Bus that handles purge broadcasts */
75 protected $purgeRelayer;
76 /** @var LoggerInterface */
77 protected $logger;
79 /** @var int ERR_* constant for the "last error" registry */
80 protected $lastRelayError = self::ERR_NONE;
82 /** Max time expected to pass between delete() and DB commit finishing */
83 const MAX_COMMIT_DELAY = 3;
84 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
85 const MAX_READ_LAG = 7;
86 /** Seconds to tombstone keys on delete() */
87 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
89 /** Seconds to keep dependency purge keys around */
90 const CHECK_KEY_TTL = self::TTL_YEAR;
91 /** Seconds to keep lock keys around */
92 const LOCK_TTL = 10;
93 /** Default remaining TTL at which to consider pre-emptive regeneration */
94 const LOW_TTL = 30;
95 /** Default time-since-expiry on a miss that makes a key "hot" */
96 const LOCK_TSE = 1;
98 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
99 const TTL_UNCACHEABLE = -1;
100 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
101 const TSE_NONE = -1;
102 /** Max TTL to store keys when a data sourced is lagged */
103 const TTL_LAGGED = 30;
104 /** Idiom for delete() for "no hold-off" */
105 const HOLDOFF_NONE = 0;
107 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
108 const TINY_NEGATIVE = -0.000001;
110 /** Cache format version number */
111 const VERSION = 1;
113 const FLD_VERSION = 0; // key to cache version number
114 const FLD_VALUE = 1; // key to the cached value
115 const FLD_TTL = 2; // key to the original TTL
116 const FLD_TIME = 3; // key to the cache time
117 const FLD_FLAGS = 4; // key to the flags bitfield
118 const FLD_HOLDOFF = 5; // key to any hold-off TTL
120 /** @var integer Treat this value as expired-on-arrival */
121 const FLG_STALE = 1;
123 const ERR_NONE = 0; // no error
124 const ERR_NO_RESPONSE = 1; // no response
125 const ERR_UNREACHABLE = 2; // can't connect
126 const ERR_UNEXPECTED = 3; // response gave some error
127 const ERR_RELAY = 4; // relay broadcast failed
129 const VALUE_KEY_PREFIX = 'WANCache:v:';
130 const INTERIM_KEY_PREFIX = 'WANCache:i:';
131 const TIME_KEY_PREFIX = 'WANCache:t:';
133 const PURGE_VAL_PREFIX = 'PURGED:';
135 const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
136 const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
138 const MAX_PC_KEYS = 1000; // max keys to keep in process cache
140 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
143 * @param array $params
144 * - cache : BagOStuff object for a persistent cache
145 * - channels : Map of (action => channel string). Actions include "purge".
146 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
147 * - logger : LoggerInterface object
149 public function __construct( array $params ) {
150 $this->cache = $params['cache'];
151 $this->procCache = new HashBagOStuff( [ 'maxKeys' => self::MAX_PC_KEYS ] );
152 $this->purgeChannel = isset( $params['channels']['purge'] )
153 ? $params['channels']['purge']
154 : self::DEFAULT_PURGE_CHANNEL;
155 $this->purgeRelayer = isset( $params['relayers']['purge'] )
156 ? $params['relayers']['purge']
157 : new EventRelayerNull( [] );
158 $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
161 public function setLogger( LoggerInterface $logger ) {
162 $this->logger = $logger;
166 * Get an instance that wraps EmptyBagOStuff
168 * @return WANObjectCache
170 public static function newEmpty() {
171 return new self( [
172 'cache' => new EmptyBagOStuff(),
173 'pool' => 'empty',
174 'relayer' => new EventRelayerNull( [] )
175 ] );
179 * Fetch the value of a key from cache
181 * If supplied, $curTTL is set to the remaining TTL (current time left):
182 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
183 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
184 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
185 * - d) null; if $key does not exist and is not tombstoned
187 * If a key is tombstoned, $curTTL will reflect the time since delete().
189 * The timestamp of $key will be checked against the last-purge timestamp
190 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
191 * initialized to the current timestamp. If any of $checkKeys have a timestamp
192 * greater than that of $key, then $curTTL will reflect how long ago $key
193 * became invalid. Callers can use $curTTL to know when the value is stale.
194 * The $checkKeys parameter allow mass invalidations by updating a single key:
195 * - a) Each "check" key represents "last purged" of some source data
196 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
197 * - c) When the source data that "check" keys represent changes,
198 * the touchCheckKey() method is called on them
200 * Source data entities might exists in a DB that uses snapshot isolation
201 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
202 * isolation can largely be maintained by doing the following:
203 * - a) Calling delete() on entity change *and* creation, before DB commit
204 * - b) Keeping transaction duration shorter than delete() hold-off TTL
206 * However, pre-snapshot values might still be seen if an update was made
207 * in a remote datacenter but the purge from delete() didn't relay yet.
209 * Consider using getWithSetCallback() instead of get() and set() cycles.
210 * That method has cache slam avoiding features for hot/expensive keys.
212 * @param string $key Cache key
213 * @param mixed $curTTL Approximate TTL left on the key if present/tombstoned [returned]
214 * @param array $checkKeys List of "check" keys
215 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
216 * @return mixed Value of cache key or false on failure
218 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
219 $curTTLs = [];
220 $asOfs = [];
221 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
222 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
223 $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null;
225 return isset( $values[$key] ) ? $values[$key] : false;
229 * Fetch the value of several keys from cache
231 * @see WANObjectCache::get()
233 * @param array $keys List of cache keys
234 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
235 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
236 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
237 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
238 * @return array Map of (key => value) for keys that exist
240 final public function getMulti(
241 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
243 $result = [];
244 $curTTLs = [];
245 $asOfs = [];
247 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
248 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
250 $checkKeysForAll = [];
251 $checkKeysByKey = [];
252 $checkKeysFlat = [];
253 foreach ( $checkKeys as $i => $keys ) {
254 $prefixed = self::prefixCacheKeys( (array)$keys, self::TIME_KEY_PREFIX );
255 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
256 // Is this check keys for a specific cache key, or for all keys being fetched?
257 if ( is_int( $i ) ) {
258 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
259 } else {
260 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
261 ? array_merge( $checkKeysByKey[$i], $prefixed )
262 : $prefixed;
266 // Fetch all of the raw values
267 $wrappedValues = $this->cache->getMulti( array_merge( $valueKeys, $checkKeysFlat ) );
268 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
269 $now = microtime( true );
271 // Collect timestamps from all "check" keys
272 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
273 $purgeValuesByKey = [];
274 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
275 $purgeValuesByKey[$cacheKey] =
276 $this->processCheckKeys( $checks, $wrappedValues, $now );
279 // Get the main cache value for each key and validate them
280 foreach ( $valueKeys as $vKey ) {
281 if ( !isset( $wrappedValues[$vKey] ) ) {
282 continue; // not found
285 $key = substr( $vKey, $vPrefixLen ); // unprefix
287 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
288 if ( $value !== false ) {
289 $result[$key] = $value;
291 // Force dependant keys to be invalid for a while after purging
292 // to reduce race conditions involving stale data getting cached
293 $purgeValues = $purgeValuesForAll;
294 if ( isset( $purgeValuesByKey[$key] ) ) {
295 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
297 foreach ( $purgeValues as $purge ) {
298 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
299 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
300 // How long ago this value was expired by *this* check key
301 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
302 // How long ago this value was expired by *any* known check key
303 $curTTL = min( $curTTL, $ago );
307 $curTTLs[$key] = $curTTL;
308 $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
311 return $result;
315 * @since 1.27
316 * @param array $timeKeys List of prefixed time check keys
317 * @param array $wrappedValues
318 * @param float $now
319 * @return array List of purge value arrays
321 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
322 $purgeValues = [];
323 foreach ( $timeKeys as $timeKey ) {
324 $purge = isset( $wrappedValues[$timeKey] )
325 ? self::parsePurgeValue( $wrappedValues[$timeKey] )
326 : false;
327 if ( $purge === false ) {
328 // Key is not set or invalid; regenerate
329 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
330 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
331 $purge = self::parsePurgeValue( $newVal );
333 $purgeValues[] = $purge;
335 return $purgeValues;
339 * Set the value of a key in cache
341 * Simply calling this method when source data changes is not valid because
342 * the changes do not replicate to the other WAN sites. In that case, delete()
343 * should be used instead. This method is intended for use on cache misses.
345 * If the data was read from a snapshot-isolated transactions (e.g. the default
346 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
347 * - a) T1 starts
348 * - b) T2 updates a row, calls delete(), and commits
349 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
350 * - d) T1 reads the row and calls set() due to a cache miss
351 * - e) Stale value is stuck in cache
353 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
355 * Example usage:
356 * @code
357 * $dbr = wfGetDB( DB_SLAVE );
358 * $setOpts = Database::getCacheSetOptions( $dbr );
359 * // Fetch the row from the DB
360 * $row = $dbr->selectRow( ... );
361 * $key = $cache->makeKey( 'building', $buildingId );
362 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
363 * @endcode
365 * @param string $key Cache key
366 * @param mixed $value
367 * @param integer $ttl Seconds to live. Special values are:
368 * - WANObjectCache::TTL_INDEFINITE: Cache forever
369 * @param array $opts Options map:
370 * - lag : Seconds of slave lag. Typically, this is either the slave lag
371 * before the data was read or, if applicable, the slave lag before
372 * the snapshot-isolated transaction the data was read from started.
373 * Default: 0 seconds
374 * - since : UNIX timestamp of the data in $value. Typically, this is either
375 * the current time the data was read or (if applicable) the time when
376 * the snapshot-isolated transaction the data was read from started.
377 * Default: 0 seconds
378 * - pending : Whether this data is possibly from an uncommitted write transaction.
379 * Generally, other threads should not see values from the future and
380 * they certainly should not see ones that ended up getting rolled back.
381 * Default: false
382 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
383 * with this TTL and flag it as stale. This is only useful if the reads for
384 * this key use getWithSetCallback() with "lockTSE" set.
385 * Default: WANObjectCache::TSE_NONE
386 * @return bool Success
388 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
389 $now = microtime( true );
390 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
391 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
392 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
394 // Do not cache potentially uncommitted data as it might get rolled back
395 if ( !empty( $opts['pending'] ) ) {
396 $this->logger->info( "Rejected set() for $key due to pending writes." );
398 return true; // no-op the write for being unsafe
401 $wrapExtra = []; // additional wrapped value fields
402 // Check if there's a risk of writing stale data after the purge tombstone expired
403 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
404 // Case A: read lag with "lockTSE"; save but record value as stale
405 if ( $lockTSE >= 0 ) {
406 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
407 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
408 // Case B: any long-running transaction; ignore this set()
409 } elseif ( $age > self::MAX_READ_LAG ) {
410 $this->logger->warning( "Rejected set() for $key due to snapshot lag." );
412 return true; // no-op the write for being unsafe
413 // Case C: high replication lag; lower TTL instead of ignoring all set()s
414 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
415 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
416 $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
417 // Case D: medium length request with medium replication lag; ignore this set()
418 } else {
419 $this->logger->warning( "Rejected set() for $key due to high read lag." );
421 return true; // no-op the write for being unsafe
425 // Wrap that value with time/TTL/version metadata
426 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
428 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
429 return ( is_string( $cWrapped ) )
430 ? false // key is tombstoned; do nothing
431 : $wrapped;
434 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl, 1 );
438 * Purge a key from all datacenters
440 * This should only be called when the underlying data (being cached)
441 * changes in a significant way. This deletes the key and starts a hold-off
442 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
443 * This is done to avoid the following race condition:
444 * - a) Some DB data changes and delete() is called on a corresponding key
445 * - b) A request refills the key with a stale value from a lagged DB
446 * - c) The stale value is stuck there until the key is expired/evicted
448 * This is implemented by storing a special "tombstone" value at the cache
449 * key that this class recognizes; get() calls will return false for the key
450 * and any set() calls will refuse to replace tombstone values at the key.
451 * For this to always avoid stale value writes, the following must hold:
452 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
453 * - b) If lag is higher, the DB will have gone into read-only mode already
455 * Note that set() can also be lag-aware and lower the TTL if it's high.
457 * When using potentially long-running ACID transactions, a good pattern is
458 * to use a pre-commit hook to issue the delete. This means that immediately
459 * after commit, callers will see the tombstone in cache in the local datacenter
460 * and in the others upon relay. It also avoids the following race condition:
461 * - a) T1 begins, changes a row, and calls delete()
462 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
463 * - c) T2 starts, reads the row and calls set() due to a cache miss
464 * - d) T1 finally commits
465 * - e) Stale value is stuck in cache
467 * Example usage:
468 * @code
469 * $dbw->begin( __METHOD__ ); // start of request
470 * ... <execute some stuff> ...
471 * // Update the row in the DB
472 * $dbw->update( ... );
473 * $key = $cache->makeKey( 'homes', $homeId );
474 * // Purge the corresponding cache entry just before committing
475 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
476 * $cache->delete( $key );
477 * } );
478 * ... <execute some stuff> ...
479 * $dbw->commit( __METHOD__ ); // end of request
480 * @endcode
482 * The $ttl parameter can be used when purging values that have not actually changed
483 * recently. For example, a cleanup script to purge cache entries does not really need
484 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
485 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
487 * If called twice on the same key, then the last hold-off TTL takes precedence. For
488 * idempotence, the $ttl should not vary for different delete() calls on the same key.
490 * @param string $key Cache key
491 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
492 * @return bool True if the item was purged or not found, false on failure
494 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
495 $key = self::VALUE_KEY_PREFIX . $key;
497 if ( $ttl <= 0 ) {
498 // Update the local datacenter immediately
499 $ok = $this->cache->delete( $key );
500 // Publish the purge to all datacenters
501 $ok = $this->relayDelete( $key ) && $ok;
502 } else {
503 // Update the local datacenter immediately
504 $ok = $this->cache->set( $key,
505 $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
506 $ttl
508 // Publish the purge to all datacenters
509 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE ) && $ok;
512 return $ok;
516 * Fetch the value of a timestamp "check" key
518 * The key will be *initialized* to the current time if not set,
519 * so only call this method if this behavior is actually desired
521 * The timestamp can be used to check whether a cached value is valid.
522 * Callers should not assume that this returns the same timestamp in
523 * all datacenters due to relay delays.
525 * The level of staleness can roughly be estimated from this key, but
526 * if the key was evicted from cache, such calculations may show the
527 * time since expiry as ~0 seconds.
529 * Note that "check" keys won't collide with other regular keys.
531 * @param string $key
532 * @return float UNIX timestamp of the check key
534 final public function getCheckKeyTime( $key ) {
535 $key = self::TIME_KEY_PREFIX . $key;
537 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
538 if ( $purge !== false ) {
539 $time = $purge[self::FLD_TIME];
540 } else {
541 // Casting assures identical floats for the next getCheckKeyTime() calls
542 $now = (string)microtime( true );
543 $this->cache->add( $key,
544 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
545 self::CHECK_KEY_TTL
547 $time = (float)$now;
550 return $time;
554 * Purge a "check" key from all datacenters, invalidating keys that use it
556 * This should only be called when the underlying data (being cached)
557 * changes in a significant way, and it is impractical to call delete()
558 * on all keys that should be changed. When get() is called on those
559 * keys, the relevant "check" keys must be supplied for this to work.
561 * The "check" key essentially represents a last-modified field.
562 * When touched, keys using it via get(), getMulti(), or getWithSetCallback()
563 * will be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
564 * by those methods to avoid race conditions where dependent keys get updated
565 * with stale values (e.g. from a DB slave).
567 * This is typically useful for keys with hardcoded names or in some cases
568 * dynamically generated names where a low number of combinations exist.
569 * When a few important keys get a large number of hits, a high cache
570 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
571 * method is less appropriate in such cases since the "time since expiry"
572 * cannot be inferred.
574 * Note that "check" keys won't collide with other regular keys.
576 * @see WANObjectCache::get()
577 * @see WANObjectCache::getWithSetCallback()
578 * @see WANObjectCache::resetCheckKey()
580 * @param string $key Cache key
581 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
582 * @return bool True if the item was purged or not found, false on failure
584 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
585 $key = self::TIME_KEY_PREFIX . $key;
586 // Update the local datacenter immediately
587 $ok = $this->cache->set( $key,
588 $this->makePurgeValue( microtime( true ), $holdoff ),
589 self::CHECK_KEY_TTL
591 // Publish the purge to all datacenters
592 return $this->relayPurge( $key, self::CHECK_KEY_TTL, $holdoff ) && $ok;
596 * Delete a "check" key from all datacenters, invalidating keys that use it
598 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
599 * or getWithSetCallback() will be invalidated. The differences are:
600 * - a) The timestamp will be deleted from all caches and lazily
601 * re-initialized when accessed (rather than set everywhere)
602 * - b) Thus, dependent keys will be known to be invalid, but not
603 * for how long (they are treated as "just" purged), which
604 * effects any lockTSE logic in getWithSetCallback()
606 * The advantage is that this does not place high TTL keys on every cache
607 * server, making it better for code that will cache many different keys
608 * and either does not use lockTSE or uses a low enough TTL anyway.
610 * This is typically useful for keys with dynamically generated names
611 * where a high number of combinations exist.
613 * Note that "check" keys won't collide with other regular keys.
615 * @see WANObjectCache::get()
616 * @see WANObjectCache::getWithSetCallback()
617 * @see WANObjectCache::touchCheckKey()
619 * @param string $key Cache key
620 * @return bool True if the item was purged or not found, false on failure
622 final public function resetCheckKey( $key ) {
623 $key = self::TIME_KEY_PREFIX . $key;
624 // Update the local datacenter immediately
625 $ok = $this->cache->delete( $key );
626 // Publish the purge to all datacenters
627 return $this->relayDelete( $key ) && $ok;
631 * Method to fetch/regenerate cache keys
633 * On cache miss, the key will be set to the callback result via set()
634 * (unless the callback returns false) and that result will be returned.
635 * The arguments supplied to the callback are:
636 * - $oldValue : current cache value or false if not present
637 * - &$ttl : a reference to the TTL which can be altered
638 * - &$setOpts : a reference to options for set() which can be altered
640 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
641 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
642 * value, but it can be used to maintain "most recent X" values that come from time or
643 * sequence based source data, provided that the "as of" id/time is tracked. Note that
644 * preemptive regeneration and $checkKeys can result in a non-false current value.
646 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
647 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
648 * regeneration will automatically be triggered using the callback.
650 * The simplest way to avoid stampedes for hot keys is to use
651 * the 'lockTSE' option in $opts. If cache purges are needed, also:
652 * - a) Pass $key into $checkKeys
653 * - b) Use touchCheckKey( $key ) instead of delete( $key )
655 * Example usage (typical key):
656 * @code
657 * $catInfo = $cache->getWithSetCallback(
658 * // Key to store the cached value under
659 * $cache->makeKey( 'cat-attributes', $catId ),
660 * // Time-to-live (in seconds)
661 * $cache::TTL_MINUTE,
662 * // Function that derives the new key value
663 * function ( $oldValue, &$ttl, array &$setOpts ) {
664 * $dbr = wfGetDB( DB_SLAVE );
665 * // Account for any snapshot/slave lag
666 * $setOpts += Database::getCacheSetOptions( $dbr );
668 * return $dbr->selectRow( ... );
670 * );
671 * @endcode
673 * Example usage (key that is expensive and hot):
674 * @code
675 * $catConfig = $cache->getWithSetCallback(
676 * // Key to store the cached value under
677 * $cache->makeKey( 'site-cat-config' ),
678 * // Time-to-live (in seconds)
679 * $cache::TTL_DAY,
680 * // Function that derives the new key value
681 * function ( $oldValue, &$ttl, array &$setOpts ) {
682 * $dbr = wfGetDB( DB_SLAVE );
683 * // Account for any snapshot/slave lag
684 * $setOpts += Database::getCacheSetOptions( $dbr );
686 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
687 * },
689 * // Calling touchCheckKey() on this key invalidates the cache
690 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
691 * // Try to only let one datacenter thread manage cache updates at a time
692 * 'lockTSE' => 30
694 * );
695 * @endcode
697 * Example usage (key with dynamic dependencies):
698 * @code
699 * $catState = $cache->getWithSetCallback(
700 * // Key to store the cached value under
701 * $cache->makeKey( 'cat-state', $cat->getId() ),
702 * // Time-to-live (seconds)
703 * $cache::TTL_HOUR,
704 * // Function that derives the new key value
705 * function ( $oldValue, &$ttl, array &$setOpts ) {
706 * // Determine new value from the DB
707 * $dbr = wfGetDB( DB_SLAVE );
708 * // Account for any snapshot/slave lag
709 * $setOpts += Database::getCacheSetOptions( $dbr );
711 * return CatState::newFromResults( $dbr->select( ... ) );
712 * },
714 * // The "check" keys that represent things the value depends on;
715 * // Calling touchCheckKey() on any of them invalidates the cache
716 * 'checkKeys' => [
717 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
718 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
719 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
722 * );
723 * @endcode
725 * Example usage (hot key holding most recent 100 events):
726 * @code
727 * $lastCatActions = $cache->getWithSetCallback(
728 * // Key to store the cached value under
729 * $cache->makeKey( 'cat-last-actions', 100 ),
730 * // Time-to-live (in seconds)
731 * 10,
732 * // Function that derives the new key value
733 * function ( $oldValue, &$ttl, array &$setOpts ) {
734 * $dbr = wfGetDB( DB_SLAVE );
735 * // Account for any snapshot/slave lag
736 * $setOpts += Database::getCacheSetOptions( $dbr );
738 * // Start off with the last cached list
739 * $list = $oldValue ?: [];
740 * // Fetch the last 100 relevant rows in descending order;
741 * // only fetch rows newer than $list[0] to reduce scanning
742 * $rows = iterator_to_array( $dbr->select( ... ) );
743 * // Merge them and get the new "last 100" rows
744 * return array_slice( array_merge( $new, $list ), 0, 100 );
745 * },
746 * // Try to only let one datacenter thread manage cache updates at a time
747 * [ 'lockTSE' => 30 ]
748 * );
749 * @endcode
751 * @see WANObjectCache::get()
752 * @see WANObjectCache::set()
754 * @param string $key Cache key
755 * @param integer $ttl Seconds to live for key updates. Special values are:
756 * - WANObjectCache::TTL_INDEFINITE: Cache forever
757 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
758 * @param callable $callback Value generation function
759 * @param array $opts Options map:
760 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
761 * touchCheckKey() or resetCheckKey() is called on any of these keys.
762 * - lowTTL: Consider pre-emptive updates when the current TTL (sec) of the key is less than
763 * this. It becomes more likely over time, becoming a certainty once the key is expired.
764 * Default: WANObjectCache::LOW_TTL seconds.
765 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
766 * ago, then try to have a single thread handle cache regeneration at any given time.
767 * Other threads will try to use stale values if possible. If, on miss, the time since
768 * expiration is low, the assumption is that the key is hot and that a stampede is worth
769 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
770 * higher this is set, the higher the worst-case staleness can be.
771 * Use WANObjectCache::TSE_NONE to disable this logic.
772 * Default: WANObjectCache::TSE_NONE.
773 * - pcTTL: Process cache the value in this PHP instance with this TTL. This avoids
774 * network I/O when a key is read several times. This will not cache if the callback
775 * returns false however. Note that any purges will not be seen while process cached;
776 * since the callback should use slave DBs and they may be lagged or have snapshot
777 * isolation anyway, this should not typically matter.
778 * Default: WANObjectCache::TTL_UNCACHEABLE.
779 * - version: Integer version number. This allows for callers to make breaking changes to
780 * how values are stored while maintaining compatability and correct cache purges. New
781 * versions are stored alongside older versions concurrently. Avoid storing class objects
782 * however, as this reduces compatibility (due to serialization).
783 * Default: null.
784 * @return mixed Value found or written to the key
786 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
787 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
789 // Try the process cache if enabled
790 $value = ( $pcTTL >= 0 ) ? $this->procCache->get( $key ) : false;
792 if ( $value === false ) {
793 unset( $opts['minTime'] ); // not a public feature
795 // Fetch the value over the network
796 if ( isset( $opts['version'] ) ) {
797 $version = $opts['version'];
798 $asOf = null;
799 $cur = $this->doGetWithSetCallback(
800 $key,
801 $ttl,
802 function ( $oldValue, &$ttl, &$setOpts ) use ( $callback, $version ) {
803 if ( is_array( $oldValue )
804 && array_key_exists( self::VFLD_DATA, $oldValue )
806 $oldData = $oldValue[self::VFLD_DATA];
807 } else {
808 // VFLD_DATA is not set if an old, unversioned, key is present
809 $oldData = false;
812 return [
813 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts ),
814 self::VFLD_VERSION => $version
817 $opts,
818 $asOf
820 if ( $cur[self::VFLD_VERSION] === $version ) {
821 // Value created or existed before with version; use it
822 $value = $cur[self::VFLD_DATA];
823 } else {
824 // Value existed before with a different version; use variant key.
825 // Reflect purges to $key by requiring that this key value be newer.
826 $value = $this->doGetWithSetCallback(
827 'cache-variant:' . md5( $key ) . ":$version",
828 $ttl,
829 $callback,
830 // Regenerate value if not newer than $key
831 [ 'version' => null, 'minTime' => $asOf ] + $opts
834 } else {
835 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
838 // Update the process cache if enabled
839 if ( $pcTTL >= 0 && $value !== false ) {
840 $this->procCache->set( $key, $value, $pcTTL );
844 return $value;
848 * Do the actual I/O for getWithSetCallback() when needed
850 * @see WANObjectCache::getWithSetCallback()
852 * @param string $key
853 * @param integer $ttl
854 * @param callback $callback
855 * @param array $opts Options map for getWithSetCallback() which also includes:
856 * - minTime: Treat values older than this UNIX timestamp as not existing. Default: null.
857 * @param float &$asOf Cache generation timestamp of returned value [returned]
858 * @return mixed
860 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
861 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
862 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
863 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
864 $minTime = isset( $opts['minTime'] ) ? $opts['minTime'] : 0.0;
865 $versioned = isset( $opts['version'] );
867 // Get the current key value
868 $curTTL = null;
869 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
870 $value = $cValue; // return value
872 // Determine if a regeneration is desired
873 if ( $value !== false
874 && $curTTL > 0
875 && $this->isValid( $value, $versioned, $asOf, $minTime )
876 && !$this->worthRefresh( $curTTL, $lowTTL )
878 return $value;
881 // A deleted key with a negative TTL left must be tombstoned
882 $isTombstone = ( $curTTL !== null && $value === false );
883 // Assume a key is hot if requested soon after invalidation
884 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
885 // Decide whether a single thread should handle regenerations.
886 // This avoids stampedes when $checkKeys are bumped and when preemptive
887 // renegerations take too long. It also reduces regenerations while $key
888 // is tombstoned. This balances cache freshness with avoiding DB load.
889 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) );
891 $lockAcquired = false;
892 if ( $useMutex ) {
893 // Acquire a datacenter-local non-blocking lock
894 if ( $this->cache->lock( $key, 0, self::LOCK_TTL ) ) {
895 // Lock acquired; this thread should update the key
896 $lockAcquired = true;
897 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
898 // If it cannot be acquired; then the stale value can be used
899 return $value;
900 } else {
901 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
902 // For hot keys, either another thread has the lock or the lock failed;
903 // use the INTERIM value from the last thread that regenerated it.
904 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
905 list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
906 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
907 $asOf = $wrapped[self::FLD_TIME];
909 return $value;
914 if ( !is_callable( $callback ) ) {
915 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
918 // Generate the new value from the callback...
919 $setOpts = [];
920 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts ] );
921 $asOf = microtime( true );
922 // When delete() is called, writes are write-holed by the tombstone,
923 // so use a special INTERIM key to pass the new value around threads.
924 if ( $useMutex && $value !== false && $ttl >= 0 ) {
925 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
926 $wrapped = $this->wrap( $value, $tempTTL, $asOf );
927 $this->cache->set( self::INTERIM_KEY_PREFIX . $key, $wrapped, $tempTTL );
930 if ( $lockAcquired ) {
931 $this->cache->unlock( $key );
934 if ( $value !== false && $ttl >= 0 ) {
935 // Update the cache; this will fail if the key is tombstoned
936 $setOpts['lockTSE'] = $lockTSE;
937 $this->set( $key, $value, $ttl, $setOpts );
940 return $value;
944 * @see BagOStuff::makeKey()
945 * @param string ... Key component
946 * @return string
947 * @since 1.27
949 public function makeKey() {
950 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
954 * @see BagOStuff::makeGlobalKey()
955 * @param string ... Key component
956 * @return string
957 * @since 1.27
959 public function makeGlobalKey() {
960 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
964 * Get the "last error" registered; clearLastError() should be called manually
965 * @return int ERR_* constant for the "last error" registry
967 final public function getLastError() {
968 if ( $this->lastRelayError ) {
969 // If the cache and the relayer failed, focus on the later.
970 // An update not making it to the relayer means it won't show up
971 // in other DCs (nor will consistent re-hashing see up-to-date values).
972 // On the other hand, if just the cache update failed, then it should
973 // eventually be applied by the relayer.
974 return $this->lastRelayError;
977 $code = $this->cache->getLastError();
978 switch ( $code ) {
979 case BagOStuff::ERR_NONE:
980 return self::ERR_NONE;
981 case BagOStuff::ERR_NO_RESPONSE:
982 return self::ERR_NO_RESPONSE;
983 case BagOStuff::ERR_UNREACHABLE:
984 return self::ERR_UNREACHABLE;
985 default:
986 return self::ERR_UNEXPECTED;
991 * Clear the "last error" registry
993 final public function clearLastError() {
994 $this->cache->clearLastError();
995 $this->lastRelayError = self::ERR_NONE;
999 * Clear the in-process caches; useful for testing
1001 * @since 1.27
1003 public function clearProcessCache() {
1004 $this->procCache->clear();
1008 * Do the actual async bus purge of a key
1010 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1012 * @param string $key Cache key
1013 * @param integer $ttl How long to keep the tombstone [seconds]
1014 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1015 * @return bool Success
1017 protected function relayPurge( $key, $ttl, $holdoff ) {
1018 $event = $this->cache->modifySimpleRelayEvent( [
1019 'cmd' => 'set',
1020 'key' => $key,
1021 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1022 'ttl' => max( $ttl, 1 ),
1023 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1024 ] );
1026 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1027 if ( !$ok ) {
1028 $this->lastRelayError = self::ERR_RELAY;
1031 return $ok;
1035 * Do the actual async bus delete of a key
1037 * @param string $key Cache key
1038 * @return bool Success
1040 protected function relayDelete( $key ) {
1041 $event = $this->cache->modifySimpleRelayEvent( [
1042 'cmd' => 'delete',
1043 'key' => $key,
1044 ] );
1046 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1047 if ( !$ok ) {
1048 $this->lastRelayError = self::ERR_RELAY;
1051 return $ok;
1055 * Check if a key should be regenerated (using random probability)
1057 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
1058 * of returning true increases steadily from 0% to 100% as the $curTTL
1059 * moves from $lowTTL to 0 seconds. This handles widely varying
1060 * levels of cache access traffic.
1062 * @param float $curTTL Approximate TTL left on the key if present
1063 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1064 * @return bool
1066 protected function worthRefresh( $curTTL, $lowTTL ) {
1067 if ( $curTTL >= $lowTTL ) {
1068 return false;
1069 } elseif ( $curTTL <= 0 ) {
1070 return true;
1073 $chance = ( 1 - $curTTL / $lowTTL );
1075 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1079 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1081 * @param array $value
1082 * @param bool $versioned
1083 * @param float $asOf The time $value was generated
1084 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1085 * @return bool
1087 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1088 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1089 return false;
1090 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1091 return false;
1094 return true;
1098 * Do not use this method outside WANObjectCache
1100 * @param mixed $value
1101 * @param integer $ttl [0=forever]
1102 * @param float $now Unix Current timestamp just before calling set()
1103 * @return array
1105 protected function wrap( $value, $ttl, $now ) {
1106 return [
1107 self::FLD_VERSION => self::VERSION,
1108 self::FLD_VALUE => $value,
1109 self::FLD_TTL => $ttl,
1110 self::FLD_TIME => $now
1115 * Do not use this method outside WANObjectCache
1117 * @param array|string|bool $wrapped
1118 * @param float $now Unix Current timestamp (preferrably pre-query)
1119 * @return array (mixed; false if absent/invalid, current time left)
1121 protected function unwrap( $wrapped, $now ) {
1122 // Check if the value is a tombstone
1123 $purge = self::parsePurgeValue( $wrapped );
1124 if ( $purge !== false ) {
1125 // Purged values should always have a negative current $ttl
1126 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1127 return [ false, $curTTL ];
1130 if ( !is_array( $wrapped ) // not found
1131 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1132 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1134 return [ false, null ];
1137 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1138 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1139 // Treat as expired, with the cache time as the expiration
1140 $age = $now - $wrapped[self::FLD_TIME];
1141 $curTTL = min( -$age, self::TINY_NEGATIVE );
1142 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1143 // Get the approximate time left on the key
1144 $age = $now - $wrapped[self::FLD_TIME];
1145 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1146 } else {
1147 // Key had no TTL, so the time left is unbounded
1148 $curTTL = INF;
1151 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1155 * @param array $keys
1156 * @param string $prefix
1157 * @return string[]
1159 protected static function prefixCacheKeys( array $keys, $prefix ) {
1160 $res = [];
1161 foreach ( $keys as $key ) {
1162 $res[] = $prefix . $key;
1165 return $res;
1169 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1170 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1171 * or false if value isn't a valid purge value
1173 protected static function parsePurgeValue( $value ) {
1174 if ( !is_string( $value ) ) {
1175 return false;
1177 $segments = explode( ':', $value, 3 );
1178 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1179 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1181 return false;
1183 if ( !isset( $segments[2] ) ) {
1184 // Back-compat with old purge values without holdoff
1185 $segments[2] = self::HOLDOFF_TTL;
1187 return [
1188 self::FLD_TIME => (float)$segments[1],
1189 self::FLD_HOLDOFF => (int)$segments[2],
1194 * @param float $timestamp
1195 * @param int $holdoff In seconds
1196 * @return string Wrapped purge value
1198 protected function makePurgeValue( $timestamp, $holdoff ) {
1199 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;