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
20 * @author Aaron Schulz
23 use Psr\Log\LoggerAwareInterface
;
24 use Psr\Log\LoggerInterface
;
25 use Psr\Log\NullLogger
;
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:s" : used for temporarily storing values of tombstoned keys
62 * - c) "WANCache:t" : used for storing timestamp "check" keys
67 class WANObjectCache
implements LoggerAwareInterface
{
68 /** @var BagOStuff The local datacenter cache */
70 /** @var HashBagOStuff Script instance PHP cache */
72 /** @var string Cache pool name */
74 /** @var EventRelayer Bus that handles purge broadcasts */
76 /** @var LoggerInterface */
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
= 31536000; // 1 year
91 /** Seconds to keep lock keys around */
93 /** Default remaining TTL at which to consider pre-emptive regeneration */
95 /** Default time-since-expiry on a miss that makes a key "hot" */
98 /** Idiom for set()/getWithSetCallback() TTL being "forever" */
99 const TTL_INDEFINITE
= 0;
100 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
101 const TTL_UNCACHEABLE
= -1;
102 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
104 /** Max TTL to store keys when a data sourced is lagged */
105 const TTL_LAGGED
= 30;
107 /** Cache format version number */
110 const FLD_VERSION
= 0;
115 const ERR_NONE
= 0; // no error
116 const ERR_NO_RESPONSE
= 1; // no response
117 const ERR_UNREACHABLE
= 2; // can't connect
118 const ERR_UNEXPECTED
= 3; // response gave some error
119 const ERR_RELAY
= 4; // relay broadcast failed
121 const VALUE_KEY_PREFIX
= 'WANCache:v:';
122 const STASH_KEY_PREFIX
= 'WANCache:s:';
123 const TIME_KEY_PREFIX
= 'WANCache:t:';
125 const PURGE_VAL_PREFIX
= 'PURGED:';
128 * @param array $params
129 * - cache : BagOStuff object
131 * - relayer : EventRelayer object
132 * - logger : LoggerInterface object
134 public function __construct( array $params ) {
135 $this->cache
= $params['cache'];
136 $this->pool
= $params['pool'];
137 $this->relayer
= $params['relayer'];
138 $this->procCache
= new HashBagOStuff();
139 $this->setLogger( isset( $params['logger'] ) ?
$params['logger'] : new NullLogger() );
142 public function setLogger( LoggerInterface
$logger ) {
143 $this->logger
= $logger;
147 * Get an instance that wraps EmptyBagOStuff
149 * @return WANObjectCache
151 public static function newEmpty() {
152 return new self( array(
153 'cache' => new EmptyBagOStuff(),
155 'relayer' => new EventRelayerNull( array() )
160 * Fetch the value of a key from cache
162 * If passed in, $curTTL is set to the remaining TTL (current time left):
163 * - a) INF; if the key exists, has no TTL, and is not expired by $checkKeys
164 * - b) float (>=0); if the key exists, has a TTL, and is not expired by $checkKeys
165 * - c) float (<0); if the key is tombstoned or existing but expired by $checkKeys
166 * - d) null; if the key does not exist and is not tombstoned
168 * If a key is tombstoned, $curTTL will reflect the time since delete().
170 * The timestamp of $key will be checked against the last-purge timestamp
171 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
172 * initialized to the current timestamp. If any of $checkKeys have a timestamp
173 * greater than that of $key, then $curTTL will reflect how long ago $key
174 * became invalid. Callers can use $curTTL to know when the value is stale.
175 * The $checkKeys parameter allow mass invalidations by updating a single key:
176 * - a) Each "check" key represents "last purged" of some source data
177 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
178 * - c) When the source data that "check" keys represent changes,
179 * the touchCheckKey() method is called on them
181 * Source data entities might exists in a DB that uses snapshot isolation
182 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
183 * isolation can largely be maintained by doing the following:
184 * - a) Calling delete() on entity change *and* creation, before DB commit
185 * - b) Keeping transaction duration shorter than delete() hold-off TTL
187 * However, pre-snapshot values might still be seen if an update was made
188 * in a remote datacenter but the purge from delete() didn't relay yet.
190 * Consider using getWithSetCallback() instead of get() and set() cycles.
191 * That method has cache slam avoiding features for hot/expensive keys.
193 * @param string $key Cache key
194 * @param mixed $curTTL Approximate TTL left on the key if present [returned]
195 * @param array $checkKeys List of "check" keys
196 * @return mixed Value of cache key or false on failure
198 final public function get( $key, &$curTTL = null, array $checkKeys = array() ) {
200 $values = $this->getMulti( array( $key ), $curTTLs, $checkKeys );
201 $curTTL = isset( $curTTLs[$key] ) ?
$curTTLs[$key] : null;
203 return isset( $values[$key] ) ?
$values[$key] : false;
207 * Fetch the value of several keys from cache
209 * @see WANObjectCache::get()
211 * @param array $keys List of cache keys
212 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
213 * @param array $checkKeys List of "check" keys to apply to all of $keys
214 * @return array Map of (key => value) for keys that exist
216 final public function getMulti(
217 array $keys, &$curTTLs = array(), array $checkKeys = array()
222 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
223 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
224 $checkKeys = self
::prefixCacheKeys( $checkKeys, self
::TIME_KEY_PREFIX
);
226 // Fetch all of the raw values
227 $wrappedValues = $this->cache
->getMulti( array_merge( $valueKeys, $checkKeys ) );
228 $now = microtime( true );
230 // Get/initialize the timestamp of all the "check" keys
231 $checkKeyTimes = array();
232 foreach ( $checkKeys as $checkKey ) {
233 $timestamp = isset( $wrappedValues[$checkKey] )
234 ? self
::parsePurgeValue( $wrappedValues[$checkKey] )
236 if ( !is_float( $timestamp ) ) {
237 // Key is not set or invalid; regenerate
238 $this->cache
->add( $checkKey,
239 self
::PURGE_VAL_PREFIX
. $now, self
::CHECK_KEY_TTL
);
243 $checkKeyTimes[] = $timestamp;
246 // Get the main cache value for each key and validate them
247 foreach ( $valueKeys as $vKey ) {
248 if ( !isset( $wrappedValues[$vKey] ) ) {
249 continue; // not found
252 $key = substr( $vKey, $vPrefixLen ); // unprefix
254 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
255 if ( $value !== false ) {
256 $result[$key] = $value;
257 foreach ( $checkKeyTimes as $checkKeyTime ) {
258 // Force dependant keys to be invalid for a while after purging
259 // to reduce race conditions involving stale data getting cached
260 $safeTimestamp = $checkKeyTime + self
::HOLDOFF_TTL
;
261 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
262 $curTTL = min( $curTTL, $checkKeyTime - $now );
267 $curTTLs[$key] = $curTTL;
274 * Set the value of a key in cache
276 * Simply calling this method when source data changes is not valid because
277 * the changes do not replicate to the other WAN sites. In that case, delete()
278 * should be used instead. This method is intended for use on cache misses.
280 * If the data was read from a snapshot-isolated transactions (e.g. the default
281 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
283 * - b) T2 updates a row, calls delete(), and commits
284 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
285 * - d) T1 reads the row and calls set() due to a cache miss
286 * - e) Stale value is stuck in cache
288 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
292 * $dbr = wfGetDB( DB_SLAVE );
293 * $setOpts = Database::getCacheSetOptions( $dbr );
294 * // Fetch the row from the DB
295 * $row = $dbr->selectRow( ... );
296 * $key = $cache->makeKey( 'building', $buildingId );
297 * $cache->set( $key, $row, 86400, $setOpts );
300 * @param string $key Cache key
301 * @param mixed $value
302 * @param integer $ttl Seconds to live. Special values are:
303 * - WANObjectCache::TTL_INDEFINITE: Cache forever
304 * @param array $opts Options map:
305 * - lag : Seconds of slave lag. Typically, this is either the slave lag
306 * before the data was read or, if applicable, the slave lag before
307 * the snapshot-isolated transaction the data was read from started.
309 * - since : UNIX timestamp of the data in $value. Typically, this is either
310 * the current time the data was read or (if applicable) the time when
311 * the snapshot-isolated transaction the data was read from started.
313 * - pending : Whether this data is possibly from an uncommitted write transaction.
314 * Generally, other threads should not see values from the future and
315 * they certainly should not see ones that ended up getting rolled back.
317 * - lockTSE : if excessive possible snapshot lag is detected,
318 * then stash the value into a temporary location
319 * with this TTL. This is only useful if the reads
320 * use getWithSetCallback() with "lockTSE" set.
321 * Default: WANObjectCache::TSE_NONE
322 * @return bool Success
324 final public function set( $key, $value, $ttl = 0, array $opts = array() ) {
325 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
326 $age = isset( $opts['since'] ) ?
max( 0, microtime( true ) - $opts['since'] ) : 0;
327 $lag = isset( $opts['lag'] ) ?
$opts['lag'] : 0;
328 // Disallow set() if the source data is uncommitted as it might get rolled back
329 if ( !empty( $opts['pending'] ) ) {
330 $this->logger
->info( "Rejected set() for $key due to pending writes." );
332 return true; // no-op the write for being unsafe
334 // Check if there's a risk of writing stale data after the purge tombstone expired
335 if ( ( $lag +
$age ) > self
::MAX_READ_LAG
) {
336 if ( $lockTSE >= 0 ) {
337 // Focus on avoiding stampedes; stash the value with a low TTL
338 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
339 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
341 // Case A: any long-running transaction; ignore this set()
342 if ( $age > self
::MAX_READ_LAG
) {
343 $this->logger
->warning( "Rejected set() for $key due to snapshot lag." );
345 return true; // no-op the write for being unsafe
346 // Case B: replication lag is high; lower TTL instead of ignoring all set()s
347 } elseif ( $lag > self
::MAX_READ_LAG
) {
348 $ttl = $ttl ?
min( $ttl, self
::TTL_LAGGED
) : self
::TTL_LAGGED
;
349 $this->logger
->warning( "Lowered set() TTL for $key due to replication lag." );
350 // Case C: medium length request during medium lag; ignore this set()
352 $this->logger
->warning( "Rejected set() for $key due to high read lag." );
354 return true; // no-op the write for being unsafe
358 $wrapped = $this->wrap( $value, $ttl );
360 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
361 return ( is_string( $cWrapped ) )
362 ?
false // key is tombstoned; do nothing
366 return $this->cache
->merge( self
::VALUE_KEY_PREFIX
. $key, $func, $ttl, 1 );
370 * Purge a key from all datacenters
372 * This should only be called when the underlying data (being cached)
373 * changes in a significant way. This deletes the key and starts a hold-off
374 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
375 * This is done to avoid the following race condition:
376 * - a) Some DB data changes and delete() is called on a corresponding key
377 * - b) A request refills the key with a stale value from a lagged DB
378 * - c) The stale value is stuck there until the key is expired/evicted
380 * This is implemented by storing a special "tombstone" value at the cache
381 * key that this class recognizes; get() calls will return false for the key
382 * and any set() calls will refuse to replace tombstone values at the key.
383 * For this to always avoid stale value writes, the following must hold:
384 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
385 * - b) If lag is higher, the DB will have gone into read-only mode already
387 * Note that set() can also be lag-aware and lower the TTL if it's high.
389 * When using potentially long-running ACID transactions, a good pattern is
390 * to use a pre-commit hook to issue the delete. This means that immediately
391 * after commit, callers will see the tombstone in cache in the local datacenter
392 * and in the others upon relay. It also avoids the following race condition:
393 * - a) T1 begins, changes a row, and calls delete()
394 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
395 * - c) T2 starts, reads the row and calls set() due to a cache miss
396 * - d) T1 finally commits
397 * - e) Stale value is stuck in cache
401 * $dbw->begin(); // start of request
402 * ... <execute some stuff> ...
403 * // Update the row in the DB
404 * $dbw->update( ... );
405 * $key = $cache->makeKey( 'homes', $homeId );
406 * // Purge the corresponding cache entry just before committing
407 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
408 * $cache->delete( $key );
410 * ... <execute some stuff> ...
411 * $dbw->commit(); // end of request
414 * If called twice on the same key, then the last hold-off TTL takes
415 * precedence. For idempotence, the $ttl should not vary for different
416 * delete() calls on the same key. Also note that lowering $ttl reduces
417 * the effective range of the 'lockTSE' parameter to getWithSetCallback().
419 * @param string $key Cache key
420 * @param integer $ttl How long to block writes to the key [seconds]
421 * @return bool True if the item was purged or not found, false on failure
423 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
424 $key = self
::VALUE_KEY_PREFIX
. $key;
425 // Avoid indefinite key salting for sanity
426 $ttl = max( $ttl, 1 );
427 // Update the local datacenter immediately
428 $ok = $this->cache
->set( $key, self
::PURGE_VAL_PREFIX
. microtime( true ), $ttl );
429 // Publish the purge to all datacenters
430 return $this->relayPurge( $key, $ttl ) && $ok;
434 * Fetch the value of a timestamp "check" key
436 * The key will be *initialized* to the current time if not set,
437 * so only call this method if this behavior is actually desired
439 * The timestamp can be used to check whether a cached value is valid.
440 * Callers should not assume that this returns the same timestamp in
441 * all datacenters due to relay delays.
443 * The level of staleness can roughly be estimated from this key, but
444 * if the key was evicted from cache, such calculations may show the
445 * time since expiry as ~0 seconds.
447 * Note that "check" keys won't collide with other regular keys.
450 * @return float UNIX timestamp of the key
452 final public function getCheckKeyTime( $key ) {
453 $key = self
::TIME_KEY_PREFIX
. $key;
455 $time = self
::parsePurgeValue( $this->cache
->get( $key ) );
456 if ( $time === false ) {
457 // Casting assures identical floats for the next getCheckKeyTime() calls
458 $time = (string)microtime( true );
459 $this->cache
->add( $key, self
::PURGE_VAL_PREFIX
. $time, self
::CHECK_KEY_TTL
);
460 $time = (float)$time;
467 * Purge a "check" key from all datacenters, invalidating keys that use it
469 * This should only be called when the underlying data (being cached)
470 * changes in a significant way, and it is impractical to call delete()
471 * on all keys that should be changed. When get() is called on those
472 * keys, the relevant "check" keys must be supplied for this to work.
474 * The "check" key essentially represents a last-modified field.
475 * When touched, keys using it via get(), getMulti(), or getWithSetCallback()
476 * will be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
477 * by those methods to avoid race conditions where dependent keys get updated
478 * with stale values (e.g. from a DB slave).
480 * This is typically useful for keys with hardcoded names or in some cases
481 * dynamically generated names where a low number of combinations exist.
482 * When a few important keys get a large number of hits, a high cache
483 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
484 * method is less appropriate in such cases since the "time since expiry"
485 * cannot be inferred.
487 * Note that "check" keys won't collide with other regular keys.
489 * @see WANObjectCache::get()
490 * @see WANObjectCache::getWithSetCallback()
491 * @see WANObjectCache::resetCheckKey()
493 * @param string $key Cache key
494 * @return bool True if the item was purged or not found, false on failure
496 final public function touchCheckKey( $key ) {
497 $key = self
::TIME_KEY_PREFIX
. $key;
498 // Update the local datacenter immediately
499 $ok = $this->cache
->set( $key,
500 self
::PURGE_VAL_PREFIX
. microtime( true ), self
::CHECK_KEY_TTL
);
501 // Publish the purge to all datacenters
502 return $this->relayPurge( $key, self
::CHECK_KEY_TTL
) && $ok;
506 * Delete a "check" key from all datacenters, invalidating keys that use it
508 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
509 * or getWithSetCallback() will be invalidated. The differences are:
510 * - a) The timestamp will be deleted from all caches and lazily
511 * re-initialized when accessed (rather than set everywhere)
512 * - b) Thus, dependent keys will be known to be invalid, but not
513 * for how long (they are treated as "just" purged), which
514 * effects any lockTSE logic in getWithSetCallback()
516 * The advantage is that this does not place high TTL keys on every cache
517 * server, making it better for code that will cache many different keys
518 * and either does not use lockTSE or uses a low enough TTL anyway.
520 * This is typically useful for keys with dynamically generated names
521 * where a high number of combinations exist.
523 * Note that "check" keys won't collide with other regular keys.
525 * @see WANObjectCache::get()
526 * @see WANObjectCache::getWithSetCallback()
527 * @see WANObjectCache::touchCheckKey()
529 * @param string $key Cache key
530 * @return bool True if the item was purged or not found, false on failure
532 final public function resetCheckKey( $key ) {
533 $key = self
::TIME_KEY_PREFIX
. $key;
534 // Update the local datacenter immediately
535 $ok = $this->cache
->delete( $key );
536 // Publish the purge to all datacenters
537 return $this->relayDelete( $key ) && $ok;
541 * Method to fetch/regenerate cache keys
543 * On cache miss, the key will be set to the callback result via set()
544 * (unless the callback returns false) and that result will be returned.
545 * The arguments supplied to the callback are:
546 * - $oldValue : current cache value or false if not present
547 * - &$ttl : a reference to the TTL which can be altered
548 * - &$setOpts : a reference to options for set() which can be altered
550 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
551 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
552 * value, but it can be used to maintain "most recent X" values that come from time or
553 * sequence based source data, provided that the "as of" id/time is tracked. Note that
554 * preemptive regeneration and $checkKeys can result in a non-false current value.
556 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
557 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
558 * regeneration will automatically be triggered using the callback.
560 * The simplest way to avoid stampedes for hot keys is to use
561 * the 'lockTSE' option in $opts. If cache purges are needed, also:
562 * - a) Pass $key into $checkKeys
563 * - b) Use touchCheckKey( $key ) instead of delete( $key )
565 * Example usage (typical key):
567 * $catInfo = $cache->getWithSetCallback(
568 * // Key to store the cached value under
569 * $cache->makeKey( 'cat-attributes', $catId ),
570 * // Time-to-live (seconds)
572 * // Function that derives the new key value
573 * function ( $oldValue, &$ttl, array &$setOpts ) {
574 * $dbr = wfGetDB( DB_SLAVE );
575 * // Account for any snapshot/slave lag
576 * $setOpts += Database::getCacheSetOptions( $dbr );
578 * return $dbr->selectRow( ... );
583 * Example usage (key that is expensive and hot):
585 * $catConfig = $cache->getWithSetCallback(
586 * // Key to store the cached value under
587 * $cache->makeKey( 'site-cat-config' ),
588 * // Time-to-live (seconds)
590 * // Function that derives the new key value
591 * function ( $oldValue, &$ttl, array &$setOpts ) {
592 * $dbr = wfGetDB( DB_SLAVE );
593 * // Account for any snapshot/slave lag
594 * $setOpts += Database::getCacheSetOptions( $dbr );
596 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
599 * // Calling touchCheckKey() on this key invalidates the cache
600 * 'checkKeys' => array( $cache->makeKey( 'site-cat-config' ) ),
601 * // Try to only let one datacenter thread manage cache updates at a time
607 * Example usage (key with dynamic dependencies):
609 * $catState = $cache->getWithSetCallback(
610 * // Key to store the cached value under
611 * $cache->makeKey( 'cat-state', $cat->getId() ),
612 * // Time-to-live (seconds)
614 * // Function that derives the new key value
615 * function ( $oldValue, &$ttl, array &$setOpts ) {
616 * // Determine new value from the DB
617 * $dbr = wfGetDB( DB_SLAVE );
618 * // Account for any snapshot/slave lag
619 * $setOpts += Database::getCacheSetOptions( $dbr );
621 * return CatState::newFromResults( $dbr->select( ... ) );
624 * // The "check" keys that represent things the value depends on;
625 * // Calling touchCheckKey() on any of them invalidates the cache
626 * 'checkKeys' => array(
627 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
628 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
629 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
635 * Example usage (hot key holding most recent 100 events):
637 * $lastCatActions = $cache->getWithSetCallback(
638 * // Key to store the cached value under
639 * $cache->makeKey( 'cat-last-actions', 100 ),
640 * // Time-to-live (seconds)
642 * // Function that derives the new key value
643 * function ( $oldValue, &$ttl, array &$setOpts ) {
644 * $dbr = wfGetDB( DB_SLAVE );
645 * // Account for any snapshot/slave lag
646 * $setOpts += Database::getCacheSetOptions( $dbr );
648 * // Start off with the last cached list
649 * $list = $oldValue ?: array();
650 * // Fetch the last 100 relevant rows in descending order;
651 * // only fetch rows newer than $list[0] to reduce scanning
652 * $rows = iterator_to_array( $dbr->select( ... ) );
653 * // Merge them and get the new "last 100" rows
654 * return array_slice( array_merge( $new, $list ), 0, 100 );
656 * // Try to only let one datacenter thread manage cache updates at a time
657 * array( 'lockTSE' => 30 )
661 * @see WANObjectCache::get()
662 * @see WANObjectCache::set()
664 * @param string $key Cache key
665 * @param integer $ttl Seconds to live for key updates. Special values are:
666 * - WANObjectCache::TTL_INDEFINITE: Cache forever
667 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
668 * @param callable $callback Value generation function
669 * @param array $opts Options map:
670 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
671 * touchCheckKey() or resetCheckKey() is called on any of these keys.
672 * - lowTTL: Consider pre-emptive updates when the current TTL (sec) of the key is less than
673 * this. It becomes more likely over time, becoming a certainty once the key is expired.
674 * Default: WANObjectCache::LOW_TTL seconds.
675 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
676 * ago, then try to have a single thread handle cache regeneration at any given time.
677 * Other threads will try to use stale values if possible. If, on miss, the time since
678 * expiration is low, the assumption is that the key is hot and that a stampede is worth
679 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
680 * higher this is set, the higher the worst-case staleness can be.
681 * Use WANObjectCache::TSE_NONE to disable this logic.
682 * Default: WANObjectCache::TSE_NONE.
683 * - pcTTL : process cache the value in this PHP instance with this TTL. This avoids
684 * network I/O when a key is read several times. This will not cache if the callback
685 * returns false however. Note that any purges will not be seen while process cached;
686 * since the callback should use slave DBs and they may be lagged or have snapshot
687 * isolation anyway, this should not typically matter.
688 * Default: WANObjectCache::TTL_UNCACHEABLE.
689 * @return mixed Value to use for the key
691 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = array() ) {
692 $pcTTL = isset( $opts['pcTTL'] ) ?
$opts['pcTTL'] : self
::TTL_UNCACHEABLE
;
694 // Try the process cache if enabled
695 $value = ( $pcTTL >= 0 ) ?
$this->procCache
->get( $key ) : false;
697 if ( $value === false ) {
698 // Fetch the value over the network
699 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
700 // Update the process cache if enabled
701 if ( $pcTTL >= 0 && $value !== false ) {
702 $this->procCache
->set( $key, $value, $pcTTL );
710 * Do the actual I/O for getWithSetCallback() when needed
712 * @see WANObjectCache::getWithSetCallback()
715 * @param integer $ttl
716 * @param callback $callback
720 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts ) {
721 $lowTTL = isset( $opts['lowTTL'] ) ?
$opts['lowTTL'] : min( self
::LOW_TTL
, $ttl );
722 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
723 $checkKeys = isset( $opts['checkKeys'] ) ?
$opts['checkKeys'] : array();
725 // Get the current key value
727 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
728 $value = $cValue; // return value
730 // Determine if a regeneration is desired
731 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
735 // A deleted key with a negative TTL left must be tombstoned
736 $isTombstone = ( $curTTL !== null && $value === false );
737 // Assume a key is hot if requested soon after invalidation
738 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
739 // Decide whether a single thread should handle regenerations.
740 // This avoids stampedes when $checkKeys are bumped and when preemptive
741 // renegerations take too long. It also reduces regenerations while $key
742 // is tombstoned. This balances cache freshness with avoiding DB load.
743 $useMutex = ( $isHot ||
( $isTombstone && $lockTSE > 0 ) );
745 $lockAcquired = false;
747 // Acquire a datacenter-local non-blocking lock
748 if ( $this->cache
->lock( $key, 0, self
::LOCK_TTL
) ) {
749 // Lock acquired; this thread should update the key
750 $lockAcquired = true;
751 } elseif ( $value !== false ) {
752 // If it cannot be acquired; then the stale value can be used
755 // Use the stash value for tombstoned keys to reduce regeneration load.
756 // For hot keys, either another thread has the lock or the lock failed;
757 // use the stash value from the last thread that regenerated it.
758 $value = $this->cache
->get( self
::STASH_KEY_PREFIX
. $key );
759 if ( $value !== false ) {
765 if ( !is_callable( $callback ) ) {
766 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
769 // Generate the new value from the callback...
771 $value = call_user_func_array( $callback, array( $cValue, &$ttl, &$setOpts ) );
772 // When delete() is called, writes are write-holed by the tombstone,
773 // so use a special stash key to pass the new value around threads.
774 if ( $useMutex && $value !== false && $ttl >= 0 ) {
775 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
776 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
779 if ( $lockAcquired ) {
780 $this->cache
->unlock( $key );
783 if ( $value !== false && $ttl >= 0 ) {
784 // Update the cache; this will fail if the key is tombstoned
785 $setOpts['lockTSE'] = $lockTSE;
786 $this->set( $key, $value, $ttl, $setOpts );
793 * @see BagOStuff::makeKey()
794 * @param string ... Key component
798 public function makeKey() {
799 return call_user_func_array( array( $this->cache
, __FUNCTION__
), func_get_args() );
803 * @see BagOStuff::makeGlobalKey()
804 * @param string ... Key component
808 public function makeGlobalKey() {
809 return call_user_func_array( array( $this->cache
, __FUNCTION__
), func_get_args() );
813 * Get the "last error" registered; clearLastError() should be called manually
814 * @return int ERR_* constant for the "last error" registry
816 final public function getLastError() {
817 if ( $this->lastRelayError
) {
818 // If the cache and the relayer failed, focus on the later.
819 // An update not making it to the relayer means it won't show up
820 // in other DCs (nor will consistent re-hashing see up-to-date values).
821 // On the other hand, if just the cache update failed, then it should
822 // eventually be applied by the relayer.
823 return $this->lastRelayError
;
826 $code = $this->cache
->getLastError();
828 case BagOStuff
::ERR_NONE
:
829 return self
::ERR_NONE
;
830 case BagOStuff
::ERR_NO_RESPONSE
:
831 return self
::ERR_NO_RESPONSE
;
832 case BagOStuff
::ERR_UNREACHABLE
:
833 return self
::ERR_UNREACHABLE
;
835 return self
::ERR_UNEXPECTED
;
840 * Clear the "last error" registry
842 final public function clearLastError() {
843 $this->cache
->clearLastError();
844 $this->lastRelayError
= self
::ERR_NONE
;
848 * Do the actual async bus purge of a key
850 * This must set the key to "PURGED:<UNIX timestamp>"
852 * @param string $key Cache key
853 * @param integer $ttl How long to keep the tombstone [seconds]
854 * @return bool Success
856 protected function relayPurge( $key, $ttl ) {
857 $event = $this->cache
->modifySimpleRelayEvent( array(
860 'val' => 'PURGED:$UNIXTIME$',
861 'ttl' => max( $ttl, 1 ),
862 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
865 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
867 $this->lastRelayError
= self
::ERR_RELAY
;
874 * Do the actual async bus delete of a key
876 * @param string $key Cache key
877 * @return bool Success
879 protected function relayDelete( $key ) {
880 $event = $this->cache
->modifySimpleRelayEvent( array(
885 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
887 $this->lastRelayError
= self
::ERR_RELAY
;
894 * Check if a key should be regenerated (using random probability)
896 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
897 * of returning true increases steadily from 0% to 100% as the $curTTL
898 * moves from $lowTTL to 0 seconds. This handles widely varying
899 * levels of cache access traffic.
901 * @param float $curTTL Approximate TTL left on the key if present
902 * @param float $lowTTL Consider a refresh when $curTTL is less than this
905 protected function worthRefresh( $curTTL, $lowTTL ) {
906 if ( $curTTL >= $lowTTL ) {
908 } elseif ( $curTTL <= 0 ) {
912 $chance = ( 1 - $curTTL / $lowTTL );
914 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
918 * Do not use this method outside WANObjectCache
920 * @param mixed $value
921 * @param integer $ttl [0=forever]
924 protected function wrap( $value, $ttl ) {
926 self
::FLD_VERSION
=> self
::VERSION
,
927 self
::FLD_VALUE
=> $value,
928 self
::FLD_TTL
=> $ttl,
929 self
::FLD_TIME
=> microtime( true )
934 * Do not use this method outside WANObjectCache
936 * @param array|string|bool $wrapped
937 * @param float $now Unix Current timestamp (preferrable pre-query)
938 * @return array (mixed; false if absent/invalid, current time left)
940 protected function unwrap( $wrapped, $now ) {
941 // Check if the value is a tombstone
942 $purgeTimestamp = self
::parsePurgeValue( $wrapped );
943 if ( is_float( $purgeTimestamp ) ) {
944 // Purged values should always have a negative current $ttl
945 $curTTL = min( -0.000001, $purgeTimestamp - $now );
946 return array( false, $curTTL );
949 if ( !is_array( $wrapped ) // not found
950 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
951 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
953 return array( false, null );
956 if ( $wrapped[self
::FLD_TTL
] > 0 ) {
957 // Get the approximate time left on the key
958 $age = $now - $wrapped[self
::FLD_TIME
];
959 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
961 // Key had no TTL, so the time left is unbounded
965 return array( $wrapped[self
::FLD_VALUE
], $curTTL );
970 * @param string $prefix
973 protected static function prefixCacheKeys( array $keys, $prefix ) {
975 foreach ( $keys as $key ) {
976 $res[] = $prefix . $key;
983 * @param string $value String like "PURGED:<timestamp>"
984 * @return float|bool UNIX timestamp or false on failure
986 protected static function parsePurgeValue( $value ) {
988 if ( is_string( $value ) &&
989 preg_match( '/^' . self
::PURGE_VAL_PREFIX
. '([^:]+)$/', $value, $m )