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 IExpiringStore
, 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
= self
::TTL_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 getWithSetCallback() callbacks to avoid calling set() */
99 const TTL_UNCACHEABLE
= -1;
100 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
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 */
113 const FLD_VERSION
= 0;
118 const FLD_HOLDOFF
= 5;
120 /** @var integer Treat this value as expired-on-arrival */
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 STASH_KEY_PREFIX
= 'WANCache:s:';
131 const TIME_KEY_PREFIX
= 'WANCache:t:';
133 const PURGE_VAL_PREFIX
= 'PURGED:';
135 const MAX_PC_KEYS
= 1000; // max keys to keep in process cache
138 * @param array $params
139 * - cache : BagOStuff object
141 * - relayer : EventRelayer object
142 * - logger : LoggerInterface object
144 public function __construct( array $params ) {
145 $this->cache
= $params['cache'];
146 $this->pool
= $params['pool'];
147 $this->relayer
= $params['relayer'];
148 $this->procCache
= new HashBagOStuff( array( 'maxKeys' => self
::MAX_PC_KEYS
) );
149 $this->setLogger( isset( $params['logger'] ) ?
$params['logger'] : new NullLogger() );
152 public function setLogger( LoggerInterface
$logger ) {
153 $this->logger
= $logger;
157 * Get an instance that wraps EmptyBagOStuff
159 * @return WANObjectCache
161 public static function newEmpty() {
162 return new self( array(
163 'cache' => new EmptyBagOStuff(),
165 'relayer' => new EventRelayerNull( array() )
170 * Fetch the value of a key from cache
172 * If supplied, $curTTL is set to the remaining TTL (current time left):
173 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
174 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
175 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
176 * - d) null; if $key does not exist and is not tombstoned
178 * If a key is tombstoned, $curTTL will reflect the time since delete().
180 * The timestamp of $key will be checked against the last-purge timestamp
181 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
182 * initialized to the current timestamp. If any of $checkKeys have a timestamp
183 * greater than that of $key, then $curTTL will reflect how long ago $key
184 * became invalid. Callers can use $curTTL to know when the value is stale.
185 * The $checkKeys parameter allow mass invalidations by updating a single key:
186 * - a) Each "check" key represents "last purged" of some source data
187 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
188 * - c) When the source data that "check" keys represent changes,
189 * the touchCheckKey() method is called on them
191 * Source data entities might exists in a DB that uses snapshot isolation
192 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
193 * isolation can largely be maintained by doing the following:
194 * - a) Calling delete() on entity change *and* creation, before DB commit
195 * - b) Keeping transaction duration shorter than delete() hold-off TTL
197 * However, pre-snapshot values might still be seen if an update was made
198 * in a remote datacenter but the purge from delete() didn't relay yet.
200 * Consider using getWithSetCallback() instead of get() and set() cycles.
201 * That method has cache slam avoiding features for hot/expensive keys.
203 * @param string $key Cache key
204 * @param mixed $curTTL Approximate TTL left on the key if present [returned]
205 * @param array $checkKeys List of "check" keys
206 * @return mixed Value of cache key or false on failure
208 final public function get( $key, &$curTTL = null, array $checkKeys = array() ) {
210 $values = $this->getMulti( array( $key ), $curTTLs, $checkKeys );
211 $curTTL = isset( $curTTLs[$key] ) ?
$curTTLs[$key] : null;
213 return isset( $values[$key] ) ?
$values[$key] : false;
217 * Fetch the value of several keys from cache
219 * @see WANObjectCache::get()
221 * @param array $keys List of cache keys
222 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
223 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
224 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
225 * @return array Map of (key => value) for keys that exist
227 final public function getMulti(
228 array $keys, &$curTTLs = array(), array $checkKeys = array()
233 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
234 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
236 $checkKeysForAll = array();
237 $checkKeysByKey = array();
238 $checkKeysFlat = array();
239 foreach ( $checkKeys as $i => $keys ) {
240 $prefixed = self
::prefixCacheKeys( (array)$keys, self
::TIME_KEY_PREFIX
);
241 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
242 // Is this check keys for a specific cache key, or for all keys being fetched?
243 if ( is_int( $i ) ) {
244 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
246 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
247 ?
array_merge( $checkKeysByKey[$i], $prefixed )
252 // Fetch all of the raw values
253 $wrappedValues = $this->cache
->getMulti( array_merge( $valueKeys, $checkKeysFlat ) );
254 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
255 $now = microtime( true );
257 // Collect timestamps from all "check" keys
258 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
259 $purgeValuesByKey = array();
260 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
261 $purgeValuesByKey[$cacheKey] =
262 $this->processCheckKeys( $checks, $wrappedValues, $now );
265 // Get the main cache value for each key and validate them
266 foreach ( $valueKeys as $vKey ) {
267 if ( !isset( $wrappedValues[$vKey] ) ) {
268 continue; // not found
271 $key = substr( $vKey, $vPrefixLen ); // unprefix
273 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
274 if ( $value !== false ) {
275 $result[$key] = $value;
277 // Force dependant keys to be invalid for a while after purging
278 // to reduce race conditions involving stale data getting cached
279 $purgeValues = $purgeValuesForAll;
280 if ( isset( $purgeValuesByKey[$key] ) ) {
281 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
283 foreach ( $purgeValues as $purge ) {
284 $safeTimestamp = $purge[self
::FLD_TIME
] +
$purge[self
::FLD_HOLDOFF
];
285 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
286 // How long ago this value was expired by *this* check key
287 $ago = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
288 // How long ago this value was expired by *any* known check key
289 $curTTL = min( $curTTL, $ago );
293 $curTTLs[$key] = $curTTL;
301 * @param array $timeKeys List of prefixed time check keys
302 * @param array $wrappedValues
304 * @return array List of purge value arrays
306 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
307 $purgeValues = array();
308 foreach ( $timeKeys as $timeKey ) {
309 $purge = isset( $wrappedValues[$timeKey] )
310 ? self
::parsePurgeValue( $wrappedValues[$timeKey] )
312 if ( $purge === false ) {
313 // Key is not set or invalid; regenerate
314 $this->cache
->add( $timeKey,
315 $this->makePurgeValue( $now, self
::HOLDOFF_TTL
),
318 $purge = array( self
::FLD_TIME
=> $now, self
::FLD_HOLDOFF
=> self
::HOLDOFF_TTL
);
320 $purgeValues[] = $purge;
326 * Set the value of a key in cache
328 * Simply calling this method when source data changes is not valid because
329 * the changes do not replicate to the other WAN sites. In that case, delete()
330 * should be used instead. This method is intended for use on cache misses.
332 * If the data was read from a snapshot-isolated transactions (e.g. the default
333 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
335 * - b) T2 updates a row, calls delete(), and commits
336 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
337 * - d) T1 reads the row and calls set() due to a cache miss
338 * - e) Stale value is stuck in cache
340 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
344 * $dbr = wfGetDB( DB_SLAVE );
345 * $setOpts = Database::getCacheSetOptions( $dbr );
346 * // Fetch the row from the DB
347 * $row = $dbr->selectRow( ... );
348 * $key = $cache->makeKey( 'building', $buildingId );
349 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
352 * @param string $key Cache key
353 * @param mixed $value
354 * @param integer $ttl Seconds to live. Special values are:
355 * - WANObjectCache::TTL_INDEFINITE: Cache forever
356 * @param array $opts Options map:
357 * - lag : Seconds of slave lag. Typically, this is either the slave lag
358 * before the data was read or, if applicable, the slave lag before
359 * the snapshot-isolated transaction the data was read from started.
361 * - since : UNIX timestamp of the data in $value. Typically, this is either
362 * the current time the data was read or (if applicable) the time when
363 * the snapshot-isolated transaction the data was read from started.
365 * - pending : Whether this data is possibly from an uncommitted write transaction.
366 * Generally, other threads should not see values from the future and
367 * they certainly should not see ones that ended up getting rolled back.
369 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
370 * with this TTL and flag it as stale. This is only useful if the reads for
371 * this key use getWithSetCallback() with "lockTSE" set.
372 * Default: WANObjectCache::TSE_NONE
373 * @return bool Success
375 final public function set( $key, $value, $ttl = 0, array $opts = array() ) {
376 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
377 $age = isset( $opts['since'] ) ?
max( 0, microtime( true ) - $opts['since'] ) : 0;
378 $lag = isset( $opts['lag'] ) ?
$opts['lag'] : 0;
380 // Do not cache potentially uncommitted data as it might get rolled back
381 if ( !empty( $opts['pending'] ) ) {
382 $this->logger
->info( "Rejected set() for $key due to pending writes." );
384 return true; // no-op the write for being unsafe
387 $wrapExtra = array(); // additional wrapped value fields
388 // Check if there's a risk of writing stale data after the purge tombstone expired
389 if ( $lag === false ||
( $lag +
$age ) > self
::MAX_READ_LAG
) {
390 // Case A: read lag with "lockTSE"; save but record value as stale
391 if ( $lockTSE >= 0 ) {
392 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
393 $wrapExtra[self
::FLD_FLAGS
] = self
::FLG_STALE
; // mark as stale
394 // Case B: any long-running transaction; ignore this set()
395 } elseif ( $age > self
::MAX_READ_LAG
) {
396 $this->logger
->warning( "Rejected set() for $key due to snapshot lag." );
398 return true; // no-op the write for being unsafe
399 // Case C: high replication lag; lower TTL instead of ignoring all set()s
400 } elseif ( $lag === false ||
$lag > self
::MAX_READ_LAG
) {
401 $ttl = $ttl ?
min( $ttl, self
::TTL_LAGGED
) : self
::TTL_LAGGED
;
402 $this->logger
->warning( "Lowered set() TTL for $key due to replication lag." );
403 // Case D: medium length request with medium replication lag; ignore this set()
405 $this->logger
->warning( "Rejected set() for $key due to high read lag." );
407 return true; // no-op the write for being unsafe
411 // Wrap that value with time/TTL/version metadata
412 $wrapped = $this->wrap( $value, $ttl ) +
$wrapExtra;
414 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
415 return ( is_string( $cWrapped ) )
416 ?
false // key is tombstoned; do nothing
420 return $this->cache
->merge( self
::VALUE_KEY_PREFIX
. $key, $func, $ttl, 1 );
424 * Purge a key from all datacenters
426 * This should only be called when the underlying data (being cached)
427 * changes in a significant way. This deletes the key and starts a hold-off
428 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
429 * This is done to avoid the following race condition:
430 * - a) Some DB data changes and delete() is called on a corresponding key
431 * - b) A request refills the key with a stale value from a lagged DB
432 * - c) The stale value is stuck there until the key is expired/evicted
434 * This is implemented by storing a special "tombstone" value at the cache
435 * key that this class recognizes; get() calls will return false for the key
436 * and any set() calls will refuse to replace tombstone values at the key.
437 * For this to always avoid stale value writes, the following must hold:
438 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
439 * - b) If lag is higher, the DB will have gone into read-only mode already
441 * Note that set() can also be lag-aware and lower the TTL if it's high.
443 * When using potentially long-running ACID transactions, a good pattern is
444 * to use a pre-commit hook to issue the delete. This means that immediately
445 * after commit, callers will see the tombstone in cache in the local datacenter
446 * and in the others upon relay. It also avoids the following race condition:
447 * - a) T1 begins, changes a row, and calls delete()
448 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
449 * - c) T2 starts, reads the row and calls set() due to a cache miss
450 * - d) T1 finally commits
451 * - e) Stale value is stuck in cache
455 * $dbw->begin(); // start of request
456 * ... <execute some stuff> ...
457 * // Update the row in the DB
458 * $dbw->update( ... );
459 * $key = $cache->makeKey( 'homes', $homeId );
460 * // Purge the corresponding cache entry just before committing
461 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
462 * $cache->delete( $key );
464 * ... <execute some stuff> ...
465 * $dbw->commit(); // end of request
468 * The $ttl parameter can be used when purging values that have not actually changed
469 * recently. For example, a cleanup script to purge cache entries does not really need
470 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
471 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
473 * If called twice on the same key, then the last hold-off TTL takes precedence. For
474 * idempotence, the $ttl should not vary for different delete() calls on the same key.
476 * @param string $key Cache key
477 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
478 * @return bool True if the item was purged or not found, false on failure
480 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
481 $key = self
::VALUE_KEY_PREFIX
. $key;
484 // Update the local datacenter immediately
485 $ok = $this->cache
->delete( $key );
486 // Publish the purge to all datacenters
487 $ok = $this->relayDelete( $key ) && $ok;
489 // Update the local datacenter immediately
490 $ok = $this->cache
->set( $key,
491 $this->makePurgeValue( microtime( true ), self
::HOLDOFF_NONE
),
494 // Publish the purge to all datacenters
495 $ok = $this->relayPurge( $key, $ttl, self
::HOLDOFF_NONE
) && $ok;
502 * Fetch the value of a timestamp "check" key
504 * The key will be *initialized* to the current time if not set,
505 * so only call this method if this behavior is actually desired
507 * The timestamp can be used to check whether a cached value is valid.
508 * Callers should not assume that this returns the same timestamp in
509 * all datacenters due to relay delays.
511 * The level of staleness can roughly be estimated from this key, but
512 * if the key was evicted from cache, such calculations may show the
513 * time since expiry as ~0 seconds.
515 * Note that "check" keys won't collide with other regular keys.
518 * @return float UNIX timestamp of the check key
520 final public function getCheckKeyTime( $key ) {
521 $key = self
::TIME_KEY_PREFIX
. $key;
523 $purge = self
::parsePurgeValue( $this->cache
->get( $key ) );
524 if ( $purge !== false ) {
525 $time = $purge[self
::FLD_TIME
];
527 // Casting assures identical floats for the next getCheckKeyTime() calls
528 $now = (string)microtime( true );
529 $this->cache
->add( $key,
530 $this->makePurgeValue( $now, self
::HOLDOFF_TTL
),
540 * Purge a "check" key from all datacenters, invalidating keys that use it
542 * This should only be called when the underlying data (being cached)
543 * changes in a significant way, and it is impractical to call delete()
544 * on all keys that should be changed. When get() is called on those
545 * keys, the relevant "check" keys must be supplied for this to work.
547 * The "check" key essentially represents a last-modified field.
548 * When touched, keys using it via get(), getMulti(), or getWithSetCallback()
549 * will be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
550 * by those methods to avoid race conditions where dependent keys get updated
551 * with stale values (e.g. from a DB slave).
553 * This is typically useful for keys with hardcoded names or in some cases
554 * dynamically generated names where a low number of combinations exist.
555 * When a few important keys get a large number of hits, a high cache
556 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
557 * method is less appropriate in such cases since the "time since expiry"
558 * cannot be inferred.
560 * Note that "check" keys won't collide with other regular keys.
562 * @see WANObjectCache::get()
563 * @see WANObjectCache::getWithSetCallback()
564 * @see WANObjectCache::resetCheckKey()
566 * @param string $key Cache key
567 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
568 * @return bool True if the item was purged or not found, false on failure
570 final public function touchCheckKey( $key, $holdoff = self
::HOLDOFF_TTL
) {
571 $key = self
::TIME_KEY_PREFIX
. $key;
572 // Update the local datacenter immediately
573 $ok = $this->cache
->set( $key,
574 $this->makePurgeValue( microtime( true ), $holdoff ),
577 // Publish the purge to all datacenters
578 return $this->relayPurge( $key, self
::CHECK_KEY_TTL
, $holdoff ) && $ok;
582 * Delete a "check" key from all datacenters, invalidating keys that use it
584 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
585 * or getWithSetCallback() will be invalidated. The differences are:
586 * - a) The timestamp will be deleted from all caches and lazily
587 * re-initialized when accessed (rather than set everywhere)
588 * - b) Thus, dependent keys will be known to be invalid, but not
589 * for how long (they are treated as "just" purged), which
590 * effects any lockTSE logic in getWithSetCallback()
592 * The advantage is that this does not place high TTL keys on every cache
593 * server, making it better for code that will cache many different keys
594 * and either does not use lockTSE or uses a low enough TTL anyway.
596 * This is typically useful for keys with dynamically generated names
597 * where a high number of combinations exist.
599 * Note that "check" keys won't collide with other regular keys.
601 * @see WANObjectCache::get()
602 * @see WANObjectCache::getWithSetCallback()
603 * @see WANObjectCache::touchCheckKey()
605 * @param string $key Cache key
606 * @return bool True if the item was purged or not found, false on failure
608 final public function resetCheckKey( $key ) {
609 $key = self
::TIME_KEY_PREFIX
. $key;
610 // Update the local datacenter immediately
611 $ok = $this->cache
->delete( $key );
612 // Publish the purge to all datacenters
613 return $this->relayDelete( $key ) && $ok;
617 * Method to fetch/regenerate cache keys
619 * On cache miss, the key will be set to the callback result via set()
620 * (unless the callback returns false) and that result will be returned.
621 * The arguments supplied to the callback are:
622 * - $oldValue : current cache value or false if not present
623 * - &$ttl : a reference to the TTL which can be altered
624 * - &$setOpts : a reference to options for set() which can be altered
626 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
627 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
628 * value, but it can be used to maintain "most recent X" values that come from time or
629 * sequence based source data, provided that the "as of" id/time is tracked. Note that
630 * preemptive regeneration and $checkKeys can result in a non-false current value.
632 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
633 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
634 * regeneration will automatically be triggered using the callback.
636 * The simplest way to avoid stampedes for hot keys is to use
637 * the 'lockTSE' option in $opts. If cache purges are needed, also:
638 * - a) Pass $key into $checkKeys
639 * - b) Use touchCheckKey( $key ) instead of delete( $key )
641 * Example usage (typical key):
643 * $catInfo = $cache->getWithSetCallback(
644 * // Key to store the cached value under
645 * $cache->makeKey( 'cat-attributes', $catId ),
646 * // Time-to-live (in seconds)
647 * $cache::TTL_MINUTE,
648 * // Function that derives the new key value
649 * function ( $oldValue, &$ttl, array &$setOpts ) {
650 * $dbr = wfGetDB( DB_SLAVE );
651 * // Account for any snapshot/slave lag
652 * $setOpts += Database::getCacheSetOptions( $dbr );
654 * return $dbr->selectRow( ... );
659 * Example usage (key that is expensive and hot):
661 * $catConfig = $cache->getWithSetCallback(
662 * // Key to store the cached value under
663 * $cache->makeKey( 'site-cat-config' ),
664 * // Time-to-live (in seconds)
666 * // Function that derives the new key value
667 * function ( $oldValue, &$ttl, array &$setOpts ) {
668 * $dbr = wfGetDB( DB_SLAVE );
669 * // Account for any snapshot/slave lag
670 * $setOpts += Database::getCacheSetOptions( $dbr );
672 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
675 * // Calling touchCheckKey() on this key invalidates the cache
676 * 'checkKeys' => array( $cache->makeKey( 'site-cat-config' ) ),
677 * // Try to only let one datacenter thread manage cache updates at a time
683 * Example usage (key with dynamic dependencies):
685 * $catState = $cache->getWithSetCallback(
686 * // Key to store the cached value under
687 * $cache->makeKey( 'cat-state', $cat->getId() ),
688 * // Time-to-live (seconds)
690 * // Function that derives the new key value
691 * function ( $oldValue, &$ttl, array &$setOpts ) {
692 * // Determine new value from the DB
693 * $dbr = wfGetDB( DB_SLAVE );
694 * // Account for any snapshot/slave lag
695 * $setOpts += Database::getCacheSetOptions( $dbr );
697 * return CatState::newFromResults( $dbr->select( ... ) );
700 * // The "check" keys that represent things the value depends on;
701 * // Calling touchCheckKey() on any of them invalidates the cache
702 * 'checkKeys' => array(
703 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
704 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
705 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
711 * Example usage (hot key holding most recent 100 events):
713 * $lastCatActions = $cache->getWithSetCallback(
714 * // Key to store the cached value under
715 * $cache->makeKey( 'cat-last-actions', 100 ),
716 * // Time-to-live (in seconds)
718 * // Function that derives the new key value
719 * function ( $oldValue, &$ttl, array &$setOpts ) {
720 * $dbr = wfGetDB( DB_SLAVE );
721 * // Account for any snapshot/slave lag
722 * $setOpts += Database::getCacheSetOptions( $dbr );
724 * // Start off with the last cached list
725 * $list = $oldValue ?: array();
726 * // Fetch the last 100 relevant rows in descending order;
727 * // only fetch rows newer than $list[0] to reduce scanning
728 * $rows = iterator_to_array( $dbr->select( ... ) );
729 * // Merge them and get the new "last 100" rows
730 * return array_slice( array_merge( $new, $list ), 0, 100 );
732 * // Try to only let one datacenter thread manage cache updates at a time
733 * array( 'lockTSE' => 30 )
737 * @see WANObjectCache::get()
738 * @see WANObjectCache::set()
740 * @param string $key Cache key
741 * @param integer $ttl Seconds to live for key updates. Special values are:
742 * - WANObjectCache::TTL_INDEFINITE: Cache forever
743 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
744 * @param callable $callback Value generation function
745 * @param array $opts Options map:
746 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
747 * touchCheckKey() or resetCheckKey() is called on any of these keys.
748 * - lowTTL: Consider pre-emptive updates when the current TTL (sec) of the key is less than
749 * this. It becomes more likely over time, becoming a certainty once the key is expired.
750 * Default: WANObjectCache::LOW_TTL seconds.
751 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
752 * ago, then try to have a single thread handle cache regeneration at any given time.
753 * Other threads will try to use stale values if possible. If, on miss, the time since
754 * expiration is low, the assumption is that the key is hot and that a stampede is worth
755 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
756 * higher this is set, the higher the worst-case staleness can be.
757 * Use WANObjectCache::TSE_NONE to disable this logic.
758 * Default: WANObjectCache::TSE_NONE.
759 * - pcTTL : process cache the value in this PHP instance with this TTL. This avoids
760 * network I/O when a key is read several times. This will not cache if the callback
761 * returns false however. Note that any purges will not be seen while process cached;
762 * since the callback should use slave DBs and they may be lagged or have snapshot
763 * isolation anyway, this should not typically matter.
764 * Default: WANObjectCache::TTL_UNCACHEABLE.
765 * @return mixed Value to use for the key
767 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = array() ) {
768 $pcTTL = isset( $opts['pcTTL'] ) ?
$opts['pcTTL'] : self
::TTL_UNCACHEABLE
;
770 // Try the process cache if enabled
771 $value = ( $pcTTL >= 0 ) ?
$this->procCache
->get( $key ) : false;
773 if ( $value === false ) {
774 // Fetch the value over the network
775 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
776 // Update the process cache if enabled
777 if ( $pcTTL >= 0 && $value !== false ) {
778 $this->procCache
->set( $key, $value, $pcTTL );
786 * Do the actual I/O for getWithSetCallback() when needed
788 * @see WANObjectCache::getWithSetCallback()
791 * @param integer $ttl
792 * @param callback $callback
796 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts ) {
797 $lowTTL = isset( $opts['lowTTL'] ) ?
$opts['lowTTL'] : min( self
::LOW_TTL
, $ttl );
798 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
799 $checkKeys = isset( $opts['checkKeys'] ) ?
$opts['checkKeys'] : array();
801 // Get the current key value
803 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
804 $value = $cValue; // return value
806 // Determine if a regeneration is desired
807 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
811 // A deleted key with a negative TTL left must be tombstoned
812 $isTombstone = ( $curTTL !== null && $value === false );
813 // Assume a key is hot if requested soon after invalidation
814 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
815 // Decide whether a single thread should handle regenerations.
816 // This avoids stampedes when $checkKeys are bumped and when preemptive
817 // renegerations take too long. It also reduces regenerations while $key
818 // is tombstoned. This balances cache freshness with avoiding DB load.
819 $useMutex = ( $isHot ||
( $isTombstone && $lockTSE > 0 ) );
821 $lockAcquired = false;
823 // Acquire a datacenter-local non-blocking lock
824 if ( $this->cache
->lock( $key, 0, self
::LOCK_TTL
) ) {
825 // Lock acquired; this thread should update the key
826 $lockAcquired = true;
827 } elseif ( $value !== false ) {
828 // If it cannot be acquired; then the stale value can be used
831 // Use the stash value for tombstoned keys to reduce regeneration load.
832 // For hot keys, either another thread has the lock or the lock failed;
833 // use the stash value from the last thread that regenerated it.
834 $value = $this->cache
->get( self
::STASH_KEY_PREFIX
. $key );
835 if ( $value !== false ) {
841 if ( !is_callable( $callback ) ) {
842 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
845 // Generate the new value from the callback...
847 $value = call_user_func_array( $callback, array( $cValue, &$ttl, &$setOpts ) );
848 // When delete() is called, writes are write-holed by the tombstone,
849 // so use a special stash key to pass the new value around threads.
850 if ( $useMutex && $value !== false && $ttl >= 0 ) {
851 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
852 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
855 if ( $lockAcquired ) {
856 $this->cache
->unlock( $key );
859 if ( $value !== false && $ttl >= 0 ) {
860 // Update the cache; this will fail if the key is tombstoned
861 $setOpts['lockTSE'] = $lockTSE;
862 $this->set( $key, $value, $ttl, $setOpts );
869 * @see BagOStuff::makeKey()
870 * @param string ... Key component
874 public function makeKey() {
875 return call_user_func_array( array( $this->cache
, __FUNCTION__
), func_get_args() );
879 * @see BagOStuff::makeGlobalKey()
880 * @param string ... Key component
884 public function makeGlobalKey() {
885 return call_user_func_array( array( $this->cache
, __FUNCTION__
), func_get_args() );
889 * Get the "last error" registered; clearLastError() should be called manually
890 * @return int ERR_* constant for the "last error" registry
892 final public function getLastError() {
893 if ( $this->lastRelayError
) {
894 // If the cache and the relayer failed, focus on the later.
895 // An update not making it to the relayer means it won't show up
896 // in other DCs (nor will consistent re-hashing see up-to-date values).
897 // On the other hand, if just the cache update failed, then it should
898 // eventually be applied by the relayer.
899 return $this->lastRelayError
;
902 $code = $this->cache
->getLastError();
904 case BagOStuff
::ERR_NONE
:
905 return self
::ERR_NONE
;
906 case BagOStuff
::ERR_NO_RESPONSE
:
907 return self
::ERR_NO_RESPONSE
;
908 case BagOStuff
::ERR_UNREACHABLE
:
909 return self
::ERR_UNREACHABLE
;
911 return self
::ERR_UNEXPECTED
;
916 * Clear the "last error" registry
918 final public function clearLastError() {
919 $this->cache
->clearLastError();
920 $this->lastRelayError
= self
::ERR_NONE
;
924 * Do the actual async bus purge of a key
926 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
928 * @param string $key Cache key
929 * @param integer $ttl How long to keep the tombstone [seconds]
930 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
931 * @return bool Success
933 protected function relayPurge( $key, $ttl, $holdoff ) {
934 $event = $this->cache
->modifySimpleRelayEvent( array(
937 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
938 'ttl' => max( $ttl, 1 ),
939 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
942 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
944 $this->lastRelayError
= self
::ERR_RELAY
;
951 * Do the actual async bus delete of a key
953 * @param string $key Cache key
954 * @return bool Success
956 protected function relayDelete( $key ) {
957 $event = $this->cache
->modifySimpleRelayEvent( array(
962 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
964 $this->lastRelayError
= self
::ERR_RELAY
;
971 * Check if a key should be regenerated (using random probability)
973 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
974 * of returning true increases steadily from 0% to 100% as the $curTTL
975 * moves from $lowTTL to 0 seconds. This handles widely varying
976 * levels of cache access traffic.
978 * @param float $curTTL Approximate TTL left on the key if present
979 * @param float $lowTTL Consider a refresh when $curTTL is less than this
982 protected function worthRefresh( $curTTL, $lowTTL ) {
983 if ( $curTTL >= $lowTTL ) {
985 } elseif ( $curTTL <= 0 ) {
989 $chance = ( 1 - $curTTL / $lowTTL );
991 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
995 * Do not use this method outside WANObjectCache
997 * @param mixed $value
998 * @param integer $ttl [0=forever]
1001 protected function wrap( $value, $ttl ) {
1003 self
::FLD_VERSION
=> self
::VERSION
,
1004 self
::FLD_VALUE
=> $value,
1005 self
::FLD_TTL
=> $ttl,
1006 self
::FLD_TIME
=> microtime( true )
1011 * Do not use this method outside WANObjectCache
1013 * @param array|string|bool $wrapped
1014 * @param float $now Unix Current timestamp (preferrable pre-query)
1015 * @return array (mixed; false if absent/invalid, current time left)
1017 protected function unwrap( $wrapped, $now ) {
1018 // Check if the value is a tombstone
1019 $purge = self
::parsePurgeValue( $wrapped );
1020 if ( $purge !== false ) {
1021 // Purged values should always have a negative current $ttl
1022 $curTTL = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
1023 return array( false, $curTTL );
1026 if ( !is_array( $wrapped ) // not found
1027 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
1028 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
1030 return array( false, null );
1033 $flags = isset( $wrapped[self
::FLD_FLAGS
] ) ?
$wrapped[self
::FLD_FLAGS
] : 0;
1034 if ( ( $flags & self
::FLG_STALE
) == self
::FLG_STALE
) {
1035 // Treat as expired, with the cache time as the expiration
1036 $age = $now - $wrapped[self
::FLD_TIME
];
1037 $curTTL = min( -$age, self
::TINY_NEGATIVE
);
1038 } elseif ( $wrapped[self
::FLD_TTL
] > 0 ) {
1039 // Get the approximate time left on the key
1040 $age = $now - $wrapped[self
::FLD_TIME
];
1041 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
1043 // Key had no TTL, so the time left is unbounded
1047 return array( $wrapped[self
::FLD_VALUE
], $curTTL );
1051 * @param array $keys
1052 * @param string $prefix
1055 protected static function prefixCacheKeys( array $keys, $prefix ) {
1057 foreach ( $keys as $key ) {
1058 $res[] = $prefix . $key;
1065 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1066 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1067 * or false if value isn't a valid purge value
1069 protected static function parsePurgeValue( $value ) {
1070 if ( !is_string( $value ) ) {
1073 $segments = explode( ':', $value, 3 );
1074 if ( !isset( $segments[0] ) ||
!isset( $segments[1] )
1075 ||
"{$segments[0]}:" !== self
::PURGE_VAL_PREFIX
1079 if ( !isset( $segments[2] ) ) {
1080 // Back-compat with old purge values without holdoff
1081 $segments[2] = self
::HOLDOFF_TTL
;
1084 self
::FLD_TIME
=> (float)$segments[1],
1085 self
::FLD_HOLDOFF
=> (int)$segments[2],
1090 * @param float $timestamp
1091 * @param int $holdoff In seconds
1092 * @return string Wrapped purge value
1094 protected function makePurgeValue( $timestamp, $holdoff ) {
1095 return self
::PURGE_VAL_PREFIX
. (float)$timestamp . ':' . (int)$holdoff;