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 lag before applying TTL_LAGGED to set() */
85 const MAX_REPLICA_LAG
= 5;
86 /** Max time since snapshot transaction start to avoid no-op of set() */
87 const MAX_SNAPSHOT_LAG
= 5;
88 /** Seconds to tombstone keys on delete() */
89 const HOLDOFF_TTL
= 14; // MAX_COMMIT_DELAY + MAX_REPLICA_LAG + MAX_SNAPSHOT_LAG + 1
91 /** Seconds to keep dependency purge keys around */
92 const CHECK_KEY_TTL
= 31536000; // 1 year
93 /** Seconds to keep lock keys around */
95 /** Default remaining TTL at which to consider pre-emptive regeneration */
97 /** Default time-since-expiry on a miss that makes a key "hot" */
100 /** Idiom for set()/getWithSetCallback() TTL being "forever" */
101 const TTL_INDEFINITE
= 0;
102 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
103 const TTL_UNCACHEABLE
= -1;
104 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
106 /** Max TTL to store keys when a data sourced is lagged */
107 const TTL_LAGGED
= 30;
109 /** Cache format version number */
112 const FLD_VERSION
= 0;
117 const ERR_NONE
= 0; // no error
118 const ERR_NO_RESPONSE
= 1; // no response
119 const ERR_UNREACHABLE
= 2; // can't connect
120 const ERR_UNEXPECTED
= 3; // response gave some error
121 const ERR_RELAY
= 4; // relay broadcast failed
123 const VALUE_KEY_PREFIX
= 'WANCache:v:';
124 const STASH_KEY_PREFIX
= 'WANCache:s:';
125 const TIME_KEY_PREFIX
= 'WANCache:t:';
127 const PURGE_VAL_PREFIX
= 'PURGED:';
130 * @param array $params
131 * - cache : BagOStuff object
133 * - relayer : EventRelayer object
134 * - logger : LoggerInterface object
136 public function __construct( array $params ) {
137 $this->cache
= $params['cache'];
138 $this->pool
= $params['pool'];
139 $this->relayer
= $params['relayer'];
140 $this->procCache
= new HashBagOStuff();
141 $this->setLogger( isset( $params['logger'] ) ?
$params['logger'] : new NullLogger() );
144 public function setLogger( LoggerInterface
$logger ) {
145 $this->logger
= $logger;
149 * Get an instance that wraps EmptyBagOStuff
151 * @return WANObjectCache
153 public static function newEmpty() {
154 return new self( array(
155 'cache' => new EmptyBagOStuff(),
157 'relayer' => new EventRelayerNull( array() )
162 * Fetch the value of a key from cache
164 * If passed in, $curTTL is set to the remaining TTL (current time left):
165 * - a) INF; if the key exists, has no TTL, and is not expired by $checkKeys
166 * - b) float (>=0); if the key exists, has a TTL, and is not expired by $checkKeys
167 * - c) float (<0); if the key is tombstoned or existing but expired by $checkKeys
168 * - d) null; if the key does not exist and is not tombstoned
170 * If a key is tombstoned, $curTTL will reflect the time since delete().
172 * The timestamp of $key will be checked against the last-purge timestamp
173 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
174 * initialized to the current timestamp. If any of $checkKeys have a timestamp
175 * greater than that of $key, then $curTTL will reflect how long ago $key
176 * became invalid. Callers can use $curTTL to know when the value is stale.
177 * The $checkKeys parameter allow mass invalidations by updating a single key:
178 * - a) Each "check" key represents "last purged" of some source data
179 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
180 * - c) When the source data that "check" keys represent changes,
181 * the touchCheckKey() method is called on them
183 * Source data entities might exists in a DB that uses snapshot isolation
184 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
185 * isolation can largely be maintained by doing the following:
186 * - a) Calling delete() on entity change *and* creation, before DB commit
187 * - b) Keeping transaction duration shorter than delete() hold-off TTL
189 * However, pre-snapshot values might still be seen if an update was made
190 * in a remote datacenter but the purge from delete() didn't relay yet.
192 * Consider using getWithSetCallback() instead of get() and set() cycles.
193 * That method has cache slam avoiding features for hot/expensive keys.
195 * @param string $key Cache key
196 * @param mixed $curTTL Approximate TTL left on the key if present [returned]
197 * @param array $checkKeys List of "check" keys
198 * @return mixed Value of cache key or false on failure
200 final public function get( $key, &$curTTL = null, array $checkKeys = array() ) {
202 $values = $this->getMulti( array( $key ), $curTTLs, $checkKeys );
203 $curTTL = isset( $curTTLs[$key] ) ?
$curTTLs[$key] : null;
205 return isset( $values[$key] ) ?
$values[$key] : false;
209 * Fetch the value of several keys from cache
211 * @see WANObjectCache::get()
213 * @param array $keys List of cache keys
214 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
215 * @param array $checkKeys List of "check" keys to apply to all of $keys
216 * @return array Map of (key => value) for keys that exist
218 final public function getMulti(
219 array $keys, &$curTTLs = array(), array $checkKeys = array()
224 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
225 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
226 $checkKeys = self
::prefixCacheKeys( $checkKeys, self
::TIME_KEY_PREFIX
);
228 // Fetch all of the raw values
229 $wrappedValues = $this->cache
->getMulti( array_merge( $valueKeys, $checkKeys ) );
230 $now = microtime( true );
232 // Get/initialize the timestamp of all the "check" keys
233 $checkKeyTimes = array();
234 foreach ( $checkKeys as $checkKey ) {
235 $timestamp = isset( $wrappedValues[$checkKey] )
236 ? self
::parsePurgeValue( $wrappedValues[$checkKey] )
238 if ( !is_float( $timestamp ) ) {
239 // Key is not set or invalid; regenerate
240 $this->cache
->add( $checkKey,
241 self
::PURGE_VAL_PREFIX
. $now, self
::CHECK_KEY_TTL
);
245 $checkKeyTimes[] = $timestamp;
248 // Get the main cache value for each key and validate them
249 foreach ( $valueKeys as $vKey ) {
250 if ( !isset( $wrappedValues[$vKey] ) ) {
251 continue; // not found
254 $key = substr( $vKey, $vPrefixLen ); // unprefix
256 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
257 if ( $value !== false ) {
258 $result[$key] = $value;
259 foreach ( $checkKeyTimes as $checkKeyTime ) {
260 // Force dependant keys to be invalid for a while after purging
261 // to reduce race conditions involving stale data getting cached
262 $safeTimestamp = $checkKeyTime + self
::HOLDOFF_TTL
;
263 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
264 $curTTL = min( $curTTL, $checkKeyTime - $now );
269 $curTTLs[$key] = $curTTL;
276 * Set the value of a key in cache
278 * Simply calling this method when source data changes is not valid because
279 * the changes do not replicate to the other WAN sites. In that case, delete()
280 * should be used instead. This method is intended for use on cache misses.
282 * If the data was read from a snapshot-isolated transactions (e.g. the default
283 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
285 * - b) T2 updates a row, calls delete(), and commits
286 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
287 * - d) T1 reads the row and calls set() due to a cache miss
288 * - e) Stale value is stuck in cache
290 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
294 * $dbr = wfGetDB( DB_SLAVE );
295 * $setOpts = Database::getCacheSetOptions( $dbr );
296 * // Fetch the row from the DB
297 * $row = $dbr->selectRow( ... );
298 * $key = $cache->makeKey( 'building', $buildingId );
299 * $cache->set( $key, $row, 86400, $setOpts );
302 * @param string $key Cache key
303 * @param mixed $value
304 * @param integer $ttl Seconds to live. Special values are:
305 * - WANObjectCache::TTL_INDEFINITE: Cache forever
306 * @param array $opts Options map:
307 * - lag : Seconds of slave lag. Typically, this is either the slave lag
308 * before the data was read or, if applicable, the slave lag before
309 * the snapshot-isolated transaction the data was read from started.
311 * - since : UNIX timestamp of the data in $value. Typically, this is either
312 * the current time the data was read or (if applicable) the time when
313 * the snapshot-isolated transaction the data was read from started.
315 * - pending : Whether this data is possibly from an uncommitted write transaction.
316 * Generally, other threads should not see values from the future and
317 * they certainly should not see ones that ended up getting rolled back.
319 * - lockTSE : if excessive possible snapshot lag is detected,
320 * then stash the value into a temporary location
321 * with this TTL. This is only useful if the reads
322 * use getWithSetCallback() with "lockTSE" set.
323 * Default: WANObjectCache::TSE_NONE
324 * @return bool Success
326 final public function set( $key, $value, $ttl = 0, array $opts = array() ) {
327 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
328 $age = isset( $opts['since'] ) ?
max( 0, microtime( true ) - $opts['since'] ) : 0;
329 $lag = isset( $opts['lag'] ) ?
$opts['lag'] : 0;
331 if ( !empty( $opts['pending'] ) ) {
332 $this->logger
->info( "Rejected set() for $key due to pending writes." );
334 return true; // no-op the write for being unsafe
337 if ( $lag > self
::MAX_REPLICA_LAG
) {
338 // Too much lag detected; lower TTL so it converges faster
339 $ttl = $ttl ?
min( $ttl, self
::TTL_LAGGED
) : self
::TTL_LAGGED
;
340 $this->logger
->warning( "Lowered set() TTL for $key due to replication lag." );
343 if ( $age > self
::MAX_SNAPSHOT_LAG
) {
344 if ( $lockTSE >= 0 ) {
345 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
346 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
348 $this->logger
->warning( "Rejected set() for $key due to snapshot lag." );
350 return true; // no-op the write for being unsafe
353 $wrapped = $this->wrap( $value, $ttl );
355 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
356 return ( is_string( $cWrapped ) )
357 ?
false // key is tombstoned; do nothing
361 return $this->cache
->merge( self
::VALUE_KEY_PREFIX
. $key, $func, $ttl, 1 );
365 * Purge a key from all datacenters
367 * This should only be called when the underlying data (being cached)
368 * changes in a significant way. This deletes the key and starts a hold-off
369 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
370 * This is done to avoid the following race condition:
371 * - a) Some DB data changes and delete() is called on a corresponding key
372 * - b) A request refills the key with a stale value from a lagged DB
373 * - c) The stale value is stuck there until the key is expired/evicted
375 * This is implemented by storing a special "tombstone" value at the cache
376 * key that this class recognizes; get() calls will return false for the key
377 * and any set() calls will refuse to replace tombstone values at the key.
378 * For this to always avoid stale value writes, the following must hold:
379 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
380 * - b) If lag is higher, the DB will have gone into read-only mode already
382 * Note that set() can also be lag-aware and lower the TTL if it's high.
384 * When using potentially long-running ACID transactions, a good pattern is
385 * to use a pre-commit hook to issue the delete. This means that immediately
386 * after commit, callers will see the tombstone in cache in the local datacenter
387 * and in the others upon relay. It also avoids the following race condition:
388 * - a) T1 begins, changes a row, and calls delete()
389 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
390 * - c) T2 starts, reads the row and calls set() due to a cache miss
391 * - d) T1 finally commits
392 * - e) Stale value is stuck in cache
396 * $dbw->begin(); // start of request
397 * ... <execute some stuff> ...
398 * // Update the row in the DB
399 * $dbw->update( ... );
400 * $key = $cache->makeKey( 'homes', $homeId );
401 * // Purge the corresponding cache entry just before committing
402 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
403 * $cache->delete( $key );
405 * ... <execute some stuff> ...
406 * $dbw->commit(); // end of request
409 * If called twice on the same key, then the last hold-off TTL takes
410 * precedence. For idempotence, the $ttl should not vary for different
411 * delete() calls on the same key. Also note that lowering $ttl reduces
412 * the effective range of the 'lockTSE' parameter to getWithSetCallback().
414 * @param string $key Cache key
415 * @param integer $ttl How long to block writes to the key [seconds]
416 * @return bool True if the item was purged or not found, false on failure
418 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
419 $key = self
::VALUE_KEY_PREFIX
. $key;
420 // Avoid indefinite key salting for sanity
421 $ttl = max( $ttl, 1 );
422 // Update the local datacenter immediately
423 $ok = $this->cache
->set( $key, self
::PURGE_VAL_PREFIX
. microtime( true ), $ttl );
424 // Publish the purge to all datacenters
425 return $this->relayPurge( $key, $ttl ) && $ok;
429 * Fetch the value of a timestamp "check" key
431 * The key will be *initialized* to the current time if not set,
432 * so only call this method if this behavior is actually desired
434 * The timestamp can be used to check whether a cached value is valid.
435 * Callers should not assume that this returns the same timestamp in
436 * all datacenters due to relay delays.
438 * The level of staleness can roughly be estimated from this key, but
439 * if the key was evicted from cache, such calculations may show the
440 * time since expiry as ~0 seconds.
442 * Note that "check" keys won't collide with other regular keys.
445 * @return float UNIX timestamp of the key
447 final public function getCheckKeyTime( $key ) {
448 $key = self
::TIME_KEY_PREFIX
. $key;
450 $time = self
::parsePurgeValue( $this->cache
->get( $key ) );
451 if ( $time === false ) {
452 // Casting assures identical floats for the next getCheckKeyTime() calls
453 $time = (string)microtime( true );
454 $this->cache
->add( $key, self
::PURGE_VAL_PREFIX
. $time, self
::CHECK_KEY_TTL
);
455 $time = (float)$time;
462 * Purge a "check" key from all datacenters, invalidating keys that use it
464 * This should only be called when the underlying data (being cached)
465 * changes in a significant way, and it is impractical to call delete()
466 * on all keys that should be changed. When get() is called on those
467 * keys, the relevant "check" keys must be supplied for this to work.
469 * The "check" key essentially represents a last-modified field.
470 * When touched, keys using it via get(), getMulti(), or getWithSetCallback()
471 * will be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
472 * by those methods to avoid race conditions where dependent keys get updated
473 * with stale values (e.g. from a DB slave).
475 * This is typically useful for keys with hardcoded names or in some cases
476 * dynamically generated names where a low number of combinations exist.
477 * When a few important keys get a large number of hits, a high cache
478 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
479 * method is less appropriate in such cases since the "time since expiry"
480 * cannot be inferred.
482 * Note that "check" keys won't collide with other regular keys.
484 * @see WANObjectCache::get()
485 * @see WANObjectCache::getWithSetCallback()
486 * @see WANObjectCache::resetCheckKey()
488 * @param string $key Cache key
489 * @return bool True if the item was purged or not found, false on failure
491 final public function touchCheckKey( $key ) {
492 $key = self
::TIME_KEY_PREFIX
. $key;
493 // Update the local datacenter immediately
494 $ok = $this->cache
->set( $key,
495 self
::PURGE_VAL_PREFIX
. microtime( true ), self
::CHECK_KEY_TTL
);
496 // Publish the purge to all datacenters
497 return $this->relayPurge( $key, self
::CHECK_KEY_TTL
) && $ok;
501 * Delete a "check" key from all datacenters, invalidating keys that use it
503 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
504 * or getWithSetCallback() will be invalidated. The differences are:
505 * - a) The timestamp will be deleted from all caches and lazily
506 * re-initialized when accessed (rather than set everywhere)
507 * - b) Thus, dependent keys will be known to be invalid, but not
508 * for how long (they are treated as "just" purged), which
509 * effects any lockTSE logic in getWithSetCallback()
511 * The advantage is that this does not place high TTL keys on every cache
512 * server, making it better for code that will cache many different keys
513 * and either does not use lockTSE or uses a low enough TTL anyway.
515 * This is typically useful for keys with dynamically generated names
516 * where a high number of combinations exist.
518 * Note that "check" keys won't collide with other regular keys.
520 * @see WANObjectCache::get()
521 * @see WANObjectCache::getWithSetCallback()
522 * @see WANObjectCache::touchCheckKey()
524 * @param string $key Cache key
525 * @return bool True if the item was purged or not found, false on failure
527 final public function resetCheckKey( $key ) {
528 $key = self
::TIME_KEY_PREFIX
. $key;
529 // Update the local datacenter immediately
530 $ok = $this->cache
->delete( $key );
531 // Publish the purge to all datacenters
532 return $this->relayDelete( $key ) && $ok;
536 * Method to fetch/regenerate cache keys
538 * On cache miss, the key will be set to the callback result via set()
539 * (unless the callback returns false) and that result will be returned.
540 * The arguments supplied to the callback are:
541 * - $oldValue : current cache value or false if not present
542 * - &$ttl : a reference to the TTL which can be altered
543 * - &$setOpts : a reference to options for set() which can be altered
545 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
546 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
547 * value, but it can be used to maintain "most recent X" values that come from time or
548 * sequence based source data, provided that the "as of" id/time is tracked. Note that
549 * preemptive regeneration and $checkKeys can result in a non-false current value.
551 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
552 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
553 * regeneration will automatically be triggered using the callback.
555 * The simplest way to avoid stampedes for hot keys is to use
556 * the 'lockTSE' option in $opts. If cache purges are needed, also:
557 * - a) Pass $key into $checkKeys
558 * - b) Use touchCheckKey( $key ) instead of delete( $key )
560 * Example usage (typical key):
562 * $catInfo = $cache->getWithSetCallback(
563 * // Key to store the cached value under
564 * $cache->makeKey( 'cat-attributes', $catId ),
565 * // Time-to-live (seconds)
567 * // Function that derives the new key value
568 * function ( $oldValue, &$ttl, array &$setOpts ) {
569 * $dbr = wfGetDB( DB_SLAVE );
570 * // Account for any snapshot/slave lag
571 * $setOpts += Database::getCacheSetOptions( $dbr );
573 * return $dbr->selectRow( ... );
578 * Example usage (key that is expensive and hot):
580 * $catConfig = $cache->getWithSetCallback(
581 * // Key to store the cached value under
582 * $cache->makeKey( 'site-cat-config' ),
583 * // Time-to-live (seconds)
585 * // Function that derives the new key value
586 * function ( $oldValue, &$ttl, array &$setOpts ) {
587 * $dbr = wfGetDB( DB_SLAVE );
588 * // Account for any snapshot/slave lag
589 * $setOpts += Database::getCacheSetOptions( $dbr );
591 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
594 * // Calling touchCheckKey() on this key invalidates the cache
595 * 'checkKeys' => array( $cache->makeKey( 'site-cat-config' ) ),
596 * // Try to only let one datacenter thread manage cache updates at a time
602 * Example usage (key with dynamic dependencies):
604 * $catState = $cache->getWithSetCallback(
605 * // Key to store the cached value under
606 * $cache->makeKey( 'cat-state', $cat->getId() ),
607 * // Time-to-live (seconds)
609 * // Function that derives the new key value
610 * function ( $oldValue, &$ttl, array &$setOpts ) {
611 * // Determine new value from the DB
612 * $dbr = wfGetDB( DB_SLAVE );
613 * // Account for any snapshot/slave lag
614 * $setOpts += Database::getCacheSetOptions( $dbr );
616 * return CatState::newFromResults( $dbr->select( ... ) );
619 * // The "check" keys that represent things the value depends on;
620 * // Calling touchCheckKey() on any of them invalidates the cache
621 * 'checkKeys' => array(
622 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
623 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
624 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
630 * Example usage (hot key holding most recent 100 events):
632 * $lastCatActions = $cache->getWithSetCallback(
633 * // Key to store the cached value under
634 * $cache->makeKey( 'cat-last-actions', 100 ),
635 * // Time-to-live (seconds)
637 * // Function that derives the new key value
638 * function ( $oldValue, &$ttl, array &$setOpts ) {
639 * $dbr = wfGetDB( DB_SLAVE );
640 * // Account for any snapshot/slave lag
641 * $setOpts += Database::getCacheSetOptions( $dbr );
643 * // Start off with the last cached list
644 * $list = $oldValue ?: array();
645 * // Fetch the last 100 relevant rows in descending order;
646 * // only fetch rows newer than $list[0] to reduce scanning
647 * $rows = iterator_to_array( $dbr->select( ... ) );
648 * // Merge them and get the new "last 100" rows
649 * return array_slice( array_merge( $new, $list ), 0, 100 );
651 * // Try to only let one datacenter thread manage cache updates at a time
652 * array( 'lockTSE' => 30 )
656 * @see WANObjectCache::get()
657 * @see WANObjectCache::set()
659 * @param string $key Cache key
660 * @param integer $ttl Seconds to live for key updates. Special values are:
661 * - WANObjectCache::TTL_INDEFINITE: Cache forever
662 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
663 * @param callable $callback Value generation function
664 * @param array $opts Options map:
665 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
666 * touchCheckKey() or resetCheckKey() is called on any of these keys.
667 * - lowTTL: Consider pre-emptive updates when the current TTL (sec) of the key is less than
668 * this. It becomes more likely over time, becoming a certainty once the key is expired.
669 * Default: WANObjectCache::LOW_TTL seconds.
670 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
671 * ago, then try to have a single thread handle cache regeneration at any given time.
672 * Other threads will try to use stale values if possible. If, on miss, the time since
673 * expiration is low, the assumption is that the key is hot and that a stampede is worth
674 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
675 * higher this is set, the higher the worst-case staleness can be.
676 * Use WANObjectCache::TSE_NONE to disable this logic.
677 * Default: WANObjectCache::TSE_NONE.
678 * - pcTTL : process cache the value in this PHP instance with this TTL. This avoids
679 * network I/O when a key is read several times. This will not cache if the callback
680 * returns false however. Note that any purges will not be seen while process cached;
681 * since the callback should use slave DBs and they may be lagged or have snapshot
682 * isolation anyway, this should not typically matter.
683 * Default: WANObjectCache::TTL_UNCACHEABLE.
684 * @return mixed Value to use for the key
686 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = array() ) {
687 $pcTTL = isset( $opts['pcTTL'] ) ?
$opts['pcTTL'] : self
::TTL_UNCACHEABLE
;
689 // Try the process cache if enabled
690 $value = ( $pcTTL >= 0 ) ?
$this->procCache
->get( $key ) : false;
692 if ( $value === false ) {
693 // Fetch the value over the network
694 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
695 // Update the process cache if enabled
696 if ( $pcTTL >= 0 && $value !== false ) {
697 $this->procCache
->set( $key, $value, $pcTTL );
705 * Do the actual I/O for getWithSetCallback() when needed
707 * @see WANObjectCache::getWithSetCallback()
710 * @param integer $ttl
711 * @param callback $callback
715 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts ) {
716 $lowTTL = isset( $opts['lowTTL'] ) ?
$opts['lowTTL'] : min( self
::LOW_TTL
, $ttl );
717 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
718 $checkKeys = isset( $opts['checkKeys'] ) ?
$opts['checkKeys'] : array();
720 // Get the current key value
722 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
723 $value = $cValue; // return value
725 // Determine if a regeneration is desired
726 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
730 // A deleted key with a negative TTL left must be tombstoned
731 $isTombstone = ( $curTTL !== null && $value === false );
732 // Assume a key is hot if requested soon after invalidation
733 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
734 // Decide whether a single thread should handle regenerations.
735 // This avoids stampedes when $checkKeys are bumped and when preemptive
736 // renegerations take too long. It also reduces regenerations while $key
737 // is tombstoned. This balances cache freshness with avoiding DB load.
738 $useMutex = ( $isHot ||
( $isTombstone && $lockTSE > 0 ) );
740 $lockAcquired = false;
742 // Acquire a datacenter-local non-blocking lock
743 if ( $this->cache
->lock( $key, 0, self
::LOCK_TTL
) ) {
744 // Lock acquired; this thread should update the key
745 $lockAcquired = true;
746 } elseif ( $value !== false ) {
747 // If it cannot be acquired; then the stale value can be used
750 // Use the stash value for tombstoned keys to reduce regeneration load.
751 // For hot keys, either another thread has the lock or the lock failed;
752 // use the stash value from the last thread that regenerated it.
753 $value = $this->cache
->get( self
::STASH_KEY_PREFIX
. $key );
754 if ( $value !== false ) {
760 if ( !is_callable( $callback ) ) {
761 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
764 // Generate the new value from the callback...
766 $value = call_user_func_array( $callback, array( $cValue, &$ttl, &$setOpts ) );
767 // When delete() is called, writes are write-holed by the tombstone,
768 // so use a special stash key to pass the new value around threads.
769 if ( $useMutex && $value !== false && $ttl >= 0 ) {
770 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
771 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
774 if ( $lockAcquired ) {
775 $this->cache
->unlock( $key );
778 if ( $value !== false && $ttl >= 0 ) {
779 // Update the cache; this will fail if the key is tombstoned
780 $setOpts['lockTSE'] = $lockTSE;
781 $this->set( $key, $value, $ttl, $setOpts );
788 * @see BagOStuff::makeKey()
789 * @param string ... Key component
793 public function makeKey() {
794 return call_user_func_array( array( $this->cache
, __FUNCTION__
), func_get_args() );
798 * @see BagOStuff::makeGlobalKey()
799 * @param string ... Key component
803 public function makeGlobalKey() {
804 return call_user_func_array( array( $this->cache
, __FUNCTION__
), func_get_args() );
808 * Get the "last error" registered; clearLastError() should be called manually
809 * @return int ERR_* constant for the "last error" registry
811 final public function getLastError() {
812 if ( $this->lastRelayError
) {
813 // If the cache and the relayer failed, focus on the later.
814 // An update not making it to the relayer means it won't show up
815 // in other DCs (nor will consistent re-hashing see up-to-date values).
816 // On the other hand, if just the cache update failed, then it should
817 // eventually be applied by the relayer.
818 return $this->lastRelayError
;
821 $code = $this->cache
->getLastError();
823 case BagOStuff
::ERR_NONE
:
824 return self
::ERR_NONE
;
825 case BagOStuff
::ERR_NO_RESPONSE
:
826 return self
::ERR_NO_RESPONSE
;
827 case BagOStuff
::ERR_UNREACHABLE
:
828 return self
::ERR_UNREACHABLE
;
830 return self
::ERR_UNEXPECTED
;
835 * Clear the "last error" registry
837 final public function clearLastError() {
838 $this->cache
->clearLastError();
839 $this->lastRelayError
= self
::ERR_NONE
;
843 * Do the actual async bus purge of a key
845 * This must set the key to "PURGED:<UNIX timestamp>"
847 * @param string $key Cache key
848 * @param integer $ttl How long to keep the tombstone [seconds]
849 * @return bool Success
851 protected function relayPurge( $key, $ttl ) {
852 $event = $this->cache
->modifySimpleRelayEvent( array(
855 'val' => 'PURGED:$UNIXTIME$',
856 'ttl' => max( $ttl, 1 ),
857 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
860 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
862 $this->lastRelayError
= self
::ERR_RELAY
;
869 * Do the actual async bus delete of a key
871 * @param string $key Cache key
872 * @return bool Success
874 protected function relayDelete( $key ) {
875 $event = $this->cache
->modifySimpleRelayEvent( array(
880 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
882 $this->lastRelayError
= self
::ERR_RELAY
;
889 * Check if a key should be regenerated (using random probability)
891 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
892 * of returning true increases steadily from 0% to 100% as the $curTTL
893 * moves from $lowTTL to 0 seconds. This handles widely varying
894 * levels of cache access traffic.
896 * @param float $curTTL Approximate TTL left on the key if present
897 * @param float $lowTTL Consider a refresh when $curTTL is less than this
900 protected function worthRefresh( $curTTL, $lowTTL ) {
901 if ( $curTTL >= $lowTTL ) {
903 } elseif ( $curTTL <= 0 ) {
907 $chance = ( 1 - $curTTL / $lowTTL );
909 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
913 * Do not use this method outside WANObjectCache
915 * @param mixed $value
916 * @param integer $ttl [0=forever]
919 protected function wrap( $value, $ttl ) {
921 self
::FLD_VERSION
=> self
::VERSION
,
922 self
::FLD_VALUE
=> $value,
923 self
::FLD_TTL
=> $ttl,
924 self
::FLD_TIME
=> microtime( true )
929 * Do not use this method outside WANObjectCache
931 * @param array|string|bool $wrapped
932 * @param float $now Unix Current timestamp (preferrable pre-query)
933 * @return array (mixed; false if absent/invalid, current time left)
935 protected function unwrap( $wrapped, $now ) {
936 // Check if the value is a tombstone
937 $purgeTimestamp = self
::parsePurgeValue( $wrapped );
938 if ( is_float( $purgeTimestamp ) ) {
939 // Purged values should always have a negative current $ttl
940 $curTTL = min( -0.000001, $purgeTimestamp - $now );
941 return array( false, $curTTL );
944 if ( !is_array( $wrapped ) // not found
945 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
946 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
948 return array( false, null );
951 if ( $wrapped[self
::FLD_TTL
] > 0 ) {
952 // Get the approximate time left on the key
953 $age = $now - $wrapped[self
::FLD_TIME
];
954 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
956 // Key had no TTL, so the time left is unbounded
960 return array( $wrapped[self
::FLD_VALUE
], $curTTL );
965 * @param string $prefix
968 protected static function prefixCacheKeys( array $keys, $prefix ) {
970 foreach ( $keys as $key ) {
971 $res[] = $prefix . $key;
978 * @param string $value String like "PURGED:<timestamp>"
979 * @return float|bool UNIX timestamp or false on failure
981 protected static function parsePurgeValue( $value ) {
983 if ( is_string( $value ) &&
984 preg_match( '/^' . self
::PURGE_VAL_PREFIX
. '([^:]+)$/', $value, $m )