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
24 * Multi-datacenter aware caching interface
26 * All operations go to the local cache, except the delete()
27 * and touchCheckKey(), which broadcast to all clusters.
28 * This class is intended for caching data from primary stores.
29 * If the get() method does not return a value, then the caller
30 * should query the new value and backfill the cache using set().
31 * When the source data changes, the delete() method should be called.
32 * Since delete() is expensive, it should be avoided. One can do so if:
33 * - a) The object cached is immutable; or
34 * - b) Validity is checked against the source after get(); or
35 * - c) Using a modest TTL is reasonably correct and performant
36 * Consider using getWithSetCallback() instead of the get()/set() cycle.
38 * Instances of this class must be configured to point to a valid
39 * PubSub endpoint, and there must be listeners on the cache servers
40 * that subscribe to the endpoint and update the caches.
42 * Broadcasted operations like delete() and touchCheckKey() are done
43 * synchronously in the local cluster, but are relayed asynchronously.
44 * This means that callers in other datacenters will see older values
45 * for a however many milliseconds the datacenters are apart. As with
46 * any cache, this should not be relied on for cases where reads are
47 * used to determine writes to source (e.g. non-cache) data stores.
49 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
50 * to avoid collisions with keys that are not wrapped as metadata arrays. The
51 * prefixes are as follows:
52 * - a) "WANCache:v" : used for regular value keys
53 * - b) "WANCache:s" : used for temporarily storing values of tombstoned keys
54 * - c) "WANCache:t" : used for storing timestamp "check" keys
59 class WANObjectCache
{
60 /** @var BagOStuff The local cluster cache */
62 /** @var string Cache pool name */
64 /** @var EventRelayer */
68 protected $lastRelayError = self
::ERR_NONE
;
70 /** Seconds to tombstone keys on delete() */
71 const HOLDOFF_TTL
= 10;
72 /** Seconds to keep dependency purge keys around */
73 const CHECK_KEY_TTL
= 31536000; // 1 year
74 /** Seconds to keep lock keys around */
77 /** Idiom for set()/getWithSetCallback() TTL */
79 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
80 const TTL_UNCACHEABLE
= -1;
82 /** Cache format version number */
85 /** Fields of value holder arrays */
86 const FLD_VERSION
= 0;
91 /** Possible values for getLastError() */
92 const ERR_NONE
= 0; // no error
93 const ERR_NO_RESPONSE
= 1; // no response
94 const ERR_UNREACHABLE
= 2; // can't connect
95 const ERR_UNEXPECTED
= 3; // response gave some error
96 const ERR_RELAY
= 4; // relay broadcast failed
98 const VALUE_KEY_PREFIX
= 'WANCache:v:';
99 const STASH_KEY_PREFIX
= 'WANCache:s:';
100 const TIME_KEY_PREFIX
= 'WANCache:t:';
102 const PURGE_VAL_PREFIX
= 'PURGED:';
105 * @param array $params
106 * - cache : BagOStuff object
108 * - relayer : EventRelayer object
110 public function __construct( array $params ) {
111 $this->cache
= $params['cache'];
112 $this->pool
= $params['pool'];
113 $this->relayer
= $params['relayer'];
117 * Fetch the value of a key from cache
119 * If passed in, $curTTL is set to the remaining TTL (current time left):
120 * - a) INF; if the key exists and has no TTL
121 * - b) float (>=0); if the key exists and has a TTL
122 * - c) float (<0); if the key is tombstoned or expired by $checkKeys
123 * - d) null; if the key does not exist and is not tombstoned
125 * If a key is tombstoned, $curTTL will reflect the time since delete().
127 * The timestamp of $key will be checked against the last-purge timestamp
128 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
129 * initialized to the current timestamp. If any of $checkKeys have a timestamp
130 * greater than that of $key, then $curTTL will reflect how long ago $key
131 * became invalid. Callers can use $curTTL to know when the value is stale.
132 * The $checkKeys parameter allow mass invalidations by updating a single key:
133 * - a) Each "check" key represents "last purged" of some source data
134 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
135 * - c) When the source data that "check" keys represent changes,
136 * the touchCheckKey() method is called on them
138 * For keys that are hot/expensive, consider using getWithSetCallback() instead.
140 * @param string $key Cache key
141 * @param mixed $curTTL Approximate TTL left on the key if present [returned]
142 * @param array $checkKeys List of "check" keys
143 * @return mixed Value of cache key or false on failure
145 final public function get( $key, &$curTTL = null, array $checkKeys = array() ) {
147 $values = $this->getMulti( array( $key ), $curTTLs, $checkKeys );
148 $curTTL = isset( $curTTLs[$key] ) ?
$curTTLs[$key] : null;
150 return isset( $values[$key] ) ?
$values[$key] : false;
154 * Fetch the value of several keys from cache
156 * @see WANObjectCache::get()
158 * @param array $keys List of cache keys
159 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
160 * @param array $checkKeys List of "check" keys
161 * @return array Map of (key => value) for keys that exist
163 final public function getMulti(
164 array $keys, &$curTTLs = array(), array $checkKeys = array()
169 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
170 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
171 $checkKeys = self
::prefixCacheKeys( $checkKeys, self
::TIME_KEY_PREFIX
);
173 // Fetch all of the raw values
174 $wrappedValues = $this->cache
->getMulti( array_merge( $valueKeys, $checkKeys ) );
175 $now = microtime( true );
177 // Get/initialize the timestamp of all the "check" keys
178 $checkKeyTimes = array();
179 foreach ( $checkKeys as $checkKey ) {
180 $timestamp = isset( $wrappedValues[$checkKey] )
181 ? self
::parsePurgeValue( $wrappedValues[$checkKey] )
183 if ( !is_float( $timestamp ) ) {
184 // Key is not set or invalid; regenerate
185 $this->cache
->add( $checkKey,
186 self
::PURGE_VAL_PREFIX
. $now, self
::CHECK_KEY_TTL
);
190 $checkKeyTimes[] = $timestamp;
193 // Get the main cache value for each key and validate them
194 foreach ( $valueKeys as $vKey ) {
195 if ( !isset( $wrappedValues[$vKey] ) ) {
196 continue; // not found
199 $key = substr( $vKey, $vPrefixLen ); // unprefix
201 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
202 if ( $value !== false ) {
203 $result[$key] = $value;
204 foreach ( $checkKeyTimes as $checkKeyTime ) {
205 // Force dependant keys to be invalid for a while after purging
206 // to reduce race conditions involving stale data getting cached
207 $safeTimestamp = $checkKeyTime + self
::HOLDOFF_TTL
;
208 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
209 $curTTL = min( $curTTL, $checkKeyTime - $now );
214 $curTTLs[$key] = $curTTL;
221 * Set the value of a key from cache
223 * Simply calling this method when source data changes is not valid because
224 * the changes do not replicate to the other WAN sites. In that case, delete()
225 * should be used instead. This method is intended for use on cache misses.
227 * @param string $key Cache key
228 * @param mixed $value
229 * @param integer $ttl Seconds to live [0=forever]
230 * @return bool Success
232 final public function set( $key, $value, $ttl = 0 ) {
233 $key = self
::VALUE_KEY_PREFIX
. $key;
234 $wrapped = $this->wrap( $value, $ttl );
236 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
237 return ( is_string( $cWrapped ) )
238 ?
false // key is tombstoned; do nothing
242 return $this->cache
->merge( $key, $func, $ttl, 1 );
246 * Purge a key from all clusters
248 * This instantiates a hold-off period where the key cannot be
249 * written to avoid race conditions where dependent keys get updated
250 * with a stale value (e.g. from a DB slave).
252 * This should only be called when the underlying data (being cached)
253 * changes in a significant way. If called twice on the same key, then
254 * the last TTL takes precedence.
256 * @param string $key Cache key
257 * @param integer $ttl How long to block writes to the key [seconds]
258 * @return bool True if the item was purged or not found, false on failure
260 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
261 $key = self
::VALUE_KEY_PREFIX
. $key;
262 // Update the local cluster immediately
263 $ok = $this->cache
->set( $key, self
::PURGE_VAL_PREFIX
. microtime( true ), $ttl );
264 // Publish the purge to all clusters
265 return $this->relayPurge( $key, $ttl ) && $ok;
269 * Fetch the value of a timestamp "check" key
271 * Note that "check" keys won't collide with other regular keys
274 * @return float|bool TS_UNIX timestamp of the key; false if not present
276 final public function getCheckKeyTime( $key ) {
277 return self
::parsePurgeValue( $this->cache
->get( self
::TIME_KEY_PREFIX
. $key ) );
281 * Purge a "check" key from all clusters, invalidating keys that use it
283 * This should only be called when the underlying data (being cached)
284 * changes in a significant way, and it is impractical to call delete()
285 * on all keys that should be changed. When get() is called on those
286 * keys, the relevant "check" keys must be supplied for this to work.
288 * The "check" key essentially represents a last-modified field.
289 * It is set in the future a few seconds when this is called, to
290 * avoid race conditions where dependent keys get updated with a
291 * stale value (e.g. from a DB slave).
293 * Note that "check" keys won't collide with other regular keys
295 * @see WANObjectCache::get()
297 * @param string $key Cache key
298 * @return bool True if the item was purged or not found, false on failure
300 final public function touchCheckKey( $key ) {
301 $key = self
::TIME_KEY_PREFIX
. $key;
302 // Update the local cluster immediately
303 $ok = $this->cache
->set( $key,
304 self
::PURGE_VAL_PREFIX
. microtime( true ), self
::CHECK_KEY_TTL
);
305 // Publish the purge to all clusters
306 return $this->relayPurge( $key, self
::CHECK_KEY_TTL
) && $ok;
310 * Method to fetch/regenerate cache keys
312 * On cache miss, the key will be set to the callback result,
313 * unless the callback returns false. The arguments supplied are:
314 * (current value or false, &$ttl)
315 * The callback function returns the new value given the current
316 * value (false if not present). Preemptive re-caching and $checkKeys
317 * can result in a non-false current value. The TTL of the new value
318 * can be set dynamically by altering $ttl in the callback (by reference).
320 * Usually, callbacks ignore the current value, but it can be used
321 * to maintain "most recent X" values that come from time or sequence
322 * based source data, provided that the "as of" id/time is tracked.
324 * Usage of $checkKeys is similar to get()/getMulti(). However,
325 * rather than the caller having to inspect a "current time left"
326 * variable (e.g. $curTTL, $curTTLs), a cache regeneration will be
327 * triggered using the callback.
329 * The simplest way to avoid stampedes for hot keys is to use
330 * the 'lockTSE' option in $opts. If cache purges are needed, also:
331 * a) Pass $key into $checkKeys
332 * b) Use touchCheckKey( $key ) instead of delete( $key )
333 * Following this pattern lets the old cache be used until a
334 * single thread updates it as needed. Also consider tweaking
335 * the 'lowTTL' parameter.
339 * $key = wfMemcKey( 'cat-recent-actions', $catId );
340 * // Function that derives the new key value given the old value
341 * $callback = function( $cValue, &$ttl ) { ... };
342 * // Get the key value from cache or from source on cache miss;
343 * // try to only let one cluster thread manage doing cache updates
344 * $opts = array( 'lockTSE' => 5, 'lowTTL' => 10 );
345 * $value = $cache->getWithSetCallback( $key, $callback, 60, array(), $opts );
350 * $key = wfMemcKey( 'cat-state', $catId );
351 * // The "check" keys that represent things the value depends on;
352 * // Calling touchCheckKey() on them invalidates "cat-state"
353 * $checkKeys = array(
354 * wfMemcKey( 'water-bowls', $houseId ),
355 * wfMemcKey( 'food-bowls', $houseId ),
356 * wfMemcKey( 'people-present', $houseId )
358 * // Function that derives the new key value
359 * $callback = function() { ... };
360 * // Get the key value from cache or from source on cache miss;
361 * // try to only let one cluster thread manage doing cache updates
362 * $opts = array( 'lockTSE' => 5, 'lowTTL' => 10 );
363 * $value = $cache->getWithSetCallback( $key, $callback, 60, $checkKeys, $opts );
366 * @see WANObjectCache::get()
368 * @param string $key Cache key
369 * @param callable $callback Value generation function
370 * @param integer $ttl Seconds to live for key updates. Special values are:
371 * - WANObjectCache::TTL_NONE : cache forever
372 * - WANObjectCache::TTL_UNCACHEABLE : do not cache at all
373 * @param array $checkKeys List of "check" keys
374 * @param array $opts Options map:
375 * - lowTTL : consider pre-emptive updates when the current TTL (sec)
376 * of the key is less than this. It becomes more likely
377 * over time, becoming a certainty once the key is expired.
378 * - lockTSE : if the key is tombstoned or expired (by $checkKeys) less
379 * than this many seconds ago, then try to have a single
380 * thread handle cache regeneration at any given time.
381 * Other threads will try to use stale values if possible.
382 * If, on miss, the time since expiration is low, the assumption
383 * is that the key is hot and that a stampede is worth avoiding.
384 * - tempTTL : when 'lockTSE' is set, this determines the TTL of the temp
385 * key used to cache values while a key is tombstoned.
386 * This avoids excessive regeneration of hot keys on delete() but
387 * may result in stale values.
388 * @return mixed Value to use for the key
390 final public function getWithSetCallback(
391 $key, $callback, $ttl, array $checkKeys = array(), array $opts = array()
393 $lowTTL = isset( $opts['lowTTL'] ) ?
$opts['lowTTL'] : min( 10, $ttl );
394 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : -1;
395 $tempTTL = isset( $opts['tempTTL'] ) ?
$opts['tempTTL'] : 5;
397 // Get the current key value
399 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
400 $value = $cValue; // return value
402 // Determine if a regeneration is desired
403 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
407 if ( !is_callable( $callback ) ) {
408 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
411 // Assume a key is hot if requested soon after invalidation
412 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
413 $isTombstone = ( $curTTL !== null && $value === false );
416 if ( $isHot ||
$isTombstone ) {
417 // Acquire a cluster-local non-blocking lock
418 if ( $this->cache
->lock( $key, 0, self
::LOCK_TTL
) ) {
419 // Lock acquired; this thread should update the key
421 } elseif ( $value !== false ) {
422 // If it cannot be acquired; then the stale value can be used
425 // Either another thread has the lock or the lock failed.
426 // Use the stash value, which is likely from the prior thread.
427 $value = $this->cache
->get( self
::STASH_KEY_PREFIX
. $key );
428 // Regenerate on timeout or if the other thread failed
429 if ( $value !== false ) {
435 // Generate the new value from the callback...
436 $value = call_user_func_array( $callback, array( $cValue, &$ttl ) );
437 // When delete() is called, writes are write-holed by the tombstone,
438 // so use a special stash key to pass the new value around threads.
439 if ( $value !== false && ( $isHot ||
$isTombstone ) && $ttl >= 0 ) {
440 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
444 $this->cache
->unlock( $key );
447 if ( $value !== false && $ttl >= 0 ) {
448 // Update the cache; this will fail if the key is tombstoned
449 $this->set( $key, $value, $ttl );
456 * Get the "last error" registered; clearLastError() should be called manually
457 * @return int ERR_* constant for the "last error" registry
459 final public function getLastError() {
460 if ( $this->lastRelayError
) {
461 // If the cache and the relayer failed, focus on the later.
462 // An update not making it to the relayer means it won't show up
463 // in other DCs (nor will consistent re-hashing see up-to-date values).
464 // On the other hand, if just the cache update failed, then it should
465 // eventually be applied by the relayer.
466 return $this->lastRelayError
;
469 $code = $this->cache
->getLastError();
471 case BagOStuff
::ERR_NONE
:
472 return self
::ERR_NONE
;
473 case BagOStuff
::ERR_NO_RESPONSE
:
474 return self
::ERR_NO_RESPONSE
;
475 case BagOStuff
::ERR_UNREACHABLE
:
476 return self
::ERR_UNREACHABLE
;
478 return self
::ERR_UNEXPECTED
;
483 * Clear the "last error" registry
485 final public function clearLastError() {
486 $this->cache
->clearLastError();
487 $this->lastRelayError
= self
::ERR_NONE
;
491 * Do the actual async bus purge of a key
493 * This must set the key to "PURGED:<UNIX timestamp>"
495 * @param string $key Cache key
496 * @param integer $ttl How long to keep the tombstone [seconds]
497 * @return bool Success
499 protected function relayPurge( $key, $ttl ) {
500 $event = $this->cache
->modifySimpleRelayEvent( array(
503 'val' => 'PURGED:$UNIXTIME$',
504 'ttl' => max( $ttl, 1 ),
505 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
508 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
510 $this->lastRelayError
= self
::ERR_RELAY
;
517 * Check if a key should be regenerated (using random probability)
519 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
520 * of returning true increases steadily from 0% to 100% as the $curTTL
521 * moves from $lowTTL to 0 seconds. This handles widely varying
522 * levels of cache access traffic.
524 * @param float|INF $curTTL Approximate TTL left on the key if present
525 * @param float $lowTTL Consider a refresh when $curTTL is less than this
528 protected function worthRefresh( $curTTL, $lowTTL ) {
529 if ( $curTTL >= $lowTTL ) {
531 } elseif ( $curTTL <= 0 ) {
535 $chance = ( 1 - $curTTL / $lowTTL );
537 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
541 * Do not use this method outside WANObjectCache
543 * @param mixed $value
544 * @param integer $ttl [0=forever]
547 protected function wrap( $value, $ttl ) {
549 self
::FLD_VERSION
=> self
::VERSION
,
550 self
::FLD_VALUE
=> $value,
551 self
::FLD_TTL
=> $ttl,
552 self
::FLD_TIME
=> microtime( true )
557 * Do not use this method outside WANObjectCache
559 * @param array|string|bool $wrapped
560 * @param float $now Unix Current timestamp (preferrable pre-query)
561 * @return array (mixed; false if absent/invalid, current time left)
563 protected function unwrap( $wrapped, $now ) {
564 // Check if the value is a tombstone
565 $purgeTimestamp = self
::parsePurgeValue( $wrapped );
566 if ( is_float( $purgeTimestamp ) ) {
567 // Purged values should always have a negative current $ttl
568 $curTTL = min( -0.000001, $purgeTimestamp - $now );
569 return array( false, $curTTL );
572 if ( !is_array( $wrapped ) // not found
573 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
574 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
576 return array( false, null );
579 if ( $wrapped[self
::FLD_TTL
] > 0 ) {
580 // Get the approximate time left on the key
581 $age = $now - $wrapped[self
::FLD_TIME
];
582 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
584 // Key had no TTL, so the time left is unbounded
588 return array( $wrapped[self
::FLD_VALUE
], $curTTL );
593 * @param string $prefix
596 protected static function prefixCacheKeys( array $keys, $prefix ) {
598 foreach ( $keys as $key ) {
599 $res[] = $prefix . $key;
606 * @param string $value String like "PURGED:<timestamp>"
607 * @return float|bool UNIX timestamp or false on failure
609 protected static function parsePurgeValue( $value ) {
611 if ( is_string( $value ) &&
612 preg_match( '/^' . self
::PURGE_VAL_PREFIX
. '([^:]+)$/', $value, $m )