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 datacenter cache, except for delete(),
27 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
29 * This class is intended for caching data from primary stores.
30 * If the get() method does not return a value, then the caller
31 * should query the new value and backfill the cache using set().
32 * When the source data changes, a purge method should be called.
33 * Since purges are expensive, they should be avoided. One can do so if:
34 * - a) The object cached is immutable; or
35 * - b) Validity is checked against the source after get(); or
36 * - c) Using a modest TTL is reasonably correct and performant
37 * The simplest purge method is delete().
39 * Instances of this class must be configured to point to a valid
40 * PubSub endpoint, and there must be listeners on the cache servers
41 * that subscribe to the endpoint and update the caches.
43 * Broadcasted operations like delete() and touchCheckKey() are done
44 * synchronously in the local datacenter, but are relayed asynchronously.
45 * This means that callers in other datacenters will see older values
46 * for however many milliseconds the datacenters are apart. As with
47 * any cache, this should not be relied on for cases where reads are
48 * used to determine writes to source (e.g. non-cache) data stores.
50 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
51 * to avoid collisions with keys that are not wrapped as metadata arrays. The
52 * prefixes are as follows:
53 * - a) "WANCache:v" : used for regular value keys
54 * - b) "WANCache:s" : used for temporarily storing values of tombstoned keys
55 * - c) "WANCache:t" : used for storing timestamp "check" keys
60 class WANObjectCache
{
61 /** @var BagOStuff The local datacenter cache */
63 /** @var string Cache pool name */
65 /** @var EventRelayer */
69 protected $lastRelayError = self
::ERR_NONE
;
71 /** Max time expected to pass between delete() and DB commit finishing */
72 const MAX_COMMIT_DELAY
= 1;
73 /** Max expected replication lag for a reasonable storage setup */
74 const MAX_REPLICA_LAG
= 7;
75 /** Max time since snapshot transaction start to avoid no-op of set() */
76 const MAX_SNAPSHOT_LAG
= 6;
77 /** Seconds to tombstone keys on delete() */
78 const HOLDOFF_TTL
= 14; // MAX_COMMIT_DELAY + MAX_REPLICA_LAG + MAX_SNAPSHOT_LAG
80 /** Seconds to keep dependency purge keys around */
81 const CHECK_KEY_TTL
= 31536000; // 1 year
82 /** Seconds to keep lock keys around */
84 /** Default remaining TTL at which to consider pre-emptive regeneration */
86 /** Default time-since-expiry on a miss that makes a key "hot" */
89 /** Idiom for set()/getWithSetCallback() TTL */
91 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
92 const TTL_UNCACHEABLE
= -1;
93 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
96 /** Cache format version number */
99 /** Fields of value holder arrays */
100 const FLD_VERSION
= 0;
105 /** Possible values for getLastError() */
106 const ERR_NONE
= 0; // no error
107 const ERR_NO_RESPONSE
= 1; // no response
108 const ERR_UNREACHABLE
= 2; // can't connect
109 const ERR_UNEXPECTED
= 3; // response gave some error
110 const ERR_RELAY
= 4; // relay broadcast failed
112 const VALUE_KEY_PREFIX
= 'WANCache:v:';
113 const STASH_KEY_PREFIX
= 'WANCache:s:';
114 const TIME_KEY_PREFIX
= 'WANCache:t:';
116 const PURGE_VAL_PREFIX
= 'PURGED:';
119 * @param array $params
120 * - cache : BagOStuff object
122 * - relayer : EventRelayer object
124 public function __construct( array $params ) {
125 $this->cache
= $params['cache'];
126 $this->pool
= $params['pool'];
127 $this->relayer
= $params['relayer'];
131 * @return WANObjectCache Cache that wraps EmptyBagOStuff
133 public static function newEmpty() {
134 return new self( array(
135 'cache' => new EmptyBagOStuff(),
137 'relayer' => new EventRelayerNull( array() )
142 * Fetch the value of a key from cache
144 * If passed in, $curTTL is set to the remaining TTL (current time left):
145 * - a) INF; if the key exists, has no TTL, and is not expired by $checkKeys
146 * - b) float (>=0); if the key exists, has a TTL, and is not expired by $checkKeys
147 * - c) float (<0); if the key is tombstoned or existing but expired by $checkKeys
148 * - d) null; if the key does not exist and is not tombstoned
150 * If a key is tombstoned, $curTTL will reflect the time since delete().
152 * The timestamp of $key will be checked against the last-purge timestamp
153 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
154 * initialized to the current timestamp. If any of $checkKeys have a timestamp
155 * greater than that of $key, then $curTTL will reflect how long ago $key
156 * became invalid. Callers can use $curTTL to know when the value is stale.
157 * The $checkKeys parameter allow mass invalidations by updating a single key:
158 * - a) Each "check" key represents "last purged" of some source data
159 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
160 * - c) When the source data that "check" keys represent changes,
161 * the touchCheckKey() method is called on them
163 * Source data entities might exists in a DB that uses snapshot isolation
164 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
165 * isolation can largely be maintained by doing the following:
166 * - a) Calling delete() on entity change *and* creation, before DB commit
167 * - b) Keeping transaction duration shorter than delete() hold-off TTL
169 * However, pre-snapshot values might still be seen if an update was made
170 * in a remote datacenter but the purge from delete() didn't relay yet.
172 * Consider using getWithSetCallback() instead of get()/set() cycles.
173 * That method has cache slam avoiding features for hot/expensive keys.
175 * @param string $key Cache key
176 * @param mixed $curTTL Approximate TTL left on the key if present [returned]
177 * @param array $checkKeys List of "check" keys
178 * @return mixed Value of cache key or false on failure
180 final public function get( $key, &$curTTL = null, array $checkKeys = array() ) {
182 $values = $this->getMulti( array( $key ), $curTTLs, $checkKeys );
183 $curTTL = isset( $curTTLs[$key] ) ?
$curTTLs[$key] : null;
185 return isset( $values[$key] ) ?
$values[$key] : false;
189 * Fetch the value of several keys from cache
191 * @see WANObjectCache::get()
193 * @param array $keys List of cache keys
194 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
195 * @param array $checkKeys List of "check" keys
196 * @return array Map of (key => value) for keys that exist
198 final public function getMulti(
199 array $keys, &$curTTLs = array(), array $checkKeys = array()
204 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
205 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
206 $checkKeys = self
::prefixCacheKeys( $checkKeys, self
::TIME_KEY_PREFIX
);
208 // Fetch all of the raw values
209 $wrappedValues = $this->cache
->getMulti( array_merge( $valueKeys, $checkKeys ) );
210 $now = microtime( true );
212 // Get/initialize the timestamp of all the "check" keys
213 $checkKeyTimes = array();
214 foreach ( $checkKeys as $checkKey ) {
215 $timestamp = isset( $wrappedValues[$checkKey] )
216 ? self
::parsePurgeValue( $wrappedValues[$checkKey] )
218 if ( !is_float( $timestamp ) ) {
219 // Key is not set or invalid; regenerate
220 $this->cache
->add( $checkKey,
221 self
::PURGE_VAL_PREFIX
. $now, self
::CHECK_KEY_TTL
);
225 $checkKeyTimes[] = $timestamp;
228 // Get the main cache value for each key and validate them
229 foreach ( $valueKeys as $vKey ) {
230 if ( !isset( $wrappedValues[$vKey] ) ) {
231 continue; // not found
234 $key = substr( $vKey, $vPrefixLen ); // unprefix
236 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
237 if ( $value !== false ) {
238 $result[$key] = $value;
239 foreach ( $checkKeyTimes as $checkKeyTime ) {
240 // Force dependant keys to be invalid for a while after purging
241 // to reduce race conditions involving stale data getting cached
242 $safeTimestamp = $checkKeyTime + self
::HOLDOFF_TTL
;
243 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
244 $curTTL = min( $curTTL, $checkKeyTime - $now );
249 $curTTLs[$key] = $curTTL;
256 * Set the value of a key from cache
258 * Simply calling this method when source data changes is not valid because
259 * the changes do not replicate to the other WAN sites. In that case, delete()
260 * should be used instead. This method is intended for use on cache misses.
262 * If the data was read from a snapshot-isolated transactions (e.g. the default
263 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
265 * - b) T2 updates a row, calls delete(), and commits
266 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
267 * - d) T1 reads the row and calls set() due to a cache miss
268 * - e) Stale value is stuck in cache
272 * $dbr = wfGetDB( DB_SLAVE );
273 * // Fetch the row from the DB
274 * $row = $dbr->selectRow( ... );
275 * $key = wfMemcKey( 'building', $buildingId );
276 * // Give the age of the transaction snapshot the data came from
277 * $opts = array( 'since' => $dbr->trxTimestamp() );
278 * $cache->set( $key, $row, 86400, $opts );
281 * @param string $key Cache key
282 * @param mixed $value
283 * @param integer $ttl Seconds to live [0=forever]
284 * @param array $opts Options map:
285 * - since : UNIX timestamp of the data in $value. Typically, this is either
286 * the current time the data was read or (if applicable) the time when
287 * the snapshot-isolated transaction the data was read from started.
288 * [Default: 0 seconds]
289 * - lockTSE : if excessive possible snapshot lag is detected,
290 * then stash the value into a temporary location
291 * with this TTL. This is only useful if the reads
292 * use getWithSetCallback() with "lockTSE" set.
293 * [Default: WANObjectCache::TSE_NONE]
294 * @return bool Success
296 final public function set( $key, $value, $ttl = 0, array $opts = array() ) {
297 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
298 $age = isset( $opts['since'] ) ?
max( 0, microtime( true ) - $opts['since'] ) : 0;
300 if ( $age > self
::MAX_SNAPSHOT_LAG
) {
301 if ( $lockTSE >= 0 ) {
302 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
303 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
306 return true; // no-op the write for being unsafe
309 $wrapped = $this->wrap( $value, $ttl );
311 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
312 return ( is_string( $cWrapped ) )
313 ?
false // key is tombstoned; do nothing
317 return $this->cache
->merge( self
::VALUE_KEY_PREFIX
. $key, $func, $ttl, 1 );
321 * Purge a key from all datacenters
323 * This should only be called when the underlying data (being cached)
324 * changes in a significant way. This deletes the key and starts a hold-off
325 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
326 * This is done to avoid the following race condition:
327 * - a) Some DB data changes and delete() is called on a corresponding key
328 * - b) A request refills the key with a stale value from a lagged DB
329 * - c) The stale value is stuck there until the key is expired/evicted
331 * This is implemented by storing a special "tombstone" value at the cache
332 * key that this class recognizes; get() calls will return false for the key
333 * and any set() calls will refuse to replace tombstone values at the key.
334 * For this to always avoid writing stale values, the following must hold:
335 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
336 * - b) If lag is higher, the DB will have gone into read-only mode already
338 * When using potentially long-running ACID transactions, a good pattern is
339 * to use a pre-commit hook to issue the delete. This means that immediately
340 * after commit, callers will see the tombstone in cache in the local datacenter
341 * and in the others upon relay. It also avoids the following race condition:
342 * - a) T1 begins, changes a row, and calls delete()
343 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
344 * - c) T2 starts, reads the row and calls set() due to a cache miss
345 * - d) T1 finally commits
346 * - e) Stale value is stuck in cache
350 * $dbw->begin(); // start of request
351 * ... <execute some stuff> ...
352 * // Update the row in the DB
353 * $dbw->update( ... );
354 * $key = wfMemcKey( 'homes', $homeId );
355 * // Purge the corresponding cache entry just before committing
356 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
357 * $cache->delete( $key );
359 * ... <execute some stuff> ...
360 * $dbw->commit(); // end of request
363 * If called twice on the same key, then the last hold-off TTL takes
364 * precedence. For idempotence, the $ttl should not vary for different
365 * delete() calls on the same key. Also note that lowering $ttl reduces
366 * the effective range of the 'lockTSE' parameter to getWithSetCallback().
368 * @param string $key Cache key
369 * @param integer $ttl How long to block writes to the key [seconds]
370 * @return bool True if the item was purged or not found, false on failure
372 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
373 $key = self
::VALUE_KEY_PREFIX
. $key;
374 // Avoid indefinite key salting for sanity
375 $ttl = max( $ttl, 1 );
376 // Update the local datacenter immediately
377 $ok = $this->cache
->set( $key, self
::PURGE_VAL_PREFIX
. microtime( true ), $ttl );
378 // Publish the purge to all datacenters
379 return $this->relayPurge( $key, $ttl ) && $ok;
383 * Fetch the value of a timestamp "check" key
385 * The key will be *initialized* to the current time if not set,
386 * so only call this method if this behavior is actually desired
388 * The timestamp can be used to check whether a cached value is valid.
389 * Callers should not assume that this returns the same timestamp in
390 * all datacenters due to relay delays.
392 * The level of staleness can roughly be estimated from this key, but
393 * if the key was evicted from cache, such calculations may show the
394 * time since expiry as ~0 seconds.
396 * Note that "check" keys won't collide with other regular keys
399 * @return float UNIX timestamp of the key
401 final public function getCheckKeyTime( $key ) {
402 $key = self
::TIME_KEY_PREFIX
. $key;
404 $time = self
::parsePurgeValue( $this->cache
->get( $key ) );
405 if ( $time === false ) {
406 // Casting assures identical floats for the next getCheckKeyTime() calls
407 $time = (string)microtime( true );
408 $this->cache
->add( $key, self
::PURGE_VAL_PREFIX
. $time, self
::CHECK_KEY_TTL
);
409 $time = (float)$time;
416 * Purge a "check" key from all datacenters, invalidating keys that use it
418 * This should only be called when the underlying data (being cached)
419 * changes in a significant way, and it is impractical to call delete()
420 * on all keys that should be changed. When get() is called on those
421 * keys, the relevant "check" keys must be supplied for this to work.
423 * The "check" key essentially represents a last-modified field.
424 * It is set in the future a few seconds when this is called, to
425 * avoid race conditions where dependent keys get updated with a
426 * stale value (e.g. from a DB slave).
428 * This is typically useful for keys with static names or some cases
429 * dynamically generated names where a low number of combinations exist.
430 * When a few important keys get a large number of hits, a high cache
431 * time is usually desired as well as lockTSE logic. The resetCheckKey()
432 * method is less appropriate in such cases since the "time since expiry"
433 * cannot be inferred.
435 * Note that "check" keys won't collide with other regular keys
437 * @see WANObjectCache::get()
439 * @param string $key Cache key
440 * @return bool True if the item was purged or not found, false on failure
442 final public function touchCheckKey( $key ) {
443 $key = self
::TIME_KEY_PREFIX
. $key;
444 // Update the local datacenter immediately
445 $ok = $this->cache
->set( $key,
446 self
::PURGE_VAL_PREFIX
. microtime( true ), self
::CHECK_KEY_TTL
);
447 // Publish the purge to all datacenters
448 return $this->relayPurge( $key, self
::CHECK_KEY_TTL
) && $ok;
452 * Delete a "check" key from all datacenters, invalidating keys that use it
454 * This is similar to touchCheckKey() in that keys using it via
455 * getWithSetCallback() will be invalidated. The differences are:
456 * - a) The timestamp will be deleted from all caches and lazily
457 * re-initialized when accessed (rather than set everywhere)
458 * - b) Thus, dependent keys will be known to be invalid, but not
459 * for how long (they are treated as "just" purged), which
460 * effects any lockTSE logic in getWithSetCallback()
462 * The advantage is that this does not place high TTL keys on every cache
463 * server, making it better for code that will cache many different keys
464 * and either does not use lockTSE or uses a low enough TTL anyway.
466 * This is typically useful for keys with dynamically generated names
467 * where a high number of combinations exist.
469 * Note that "check" keys won't collide with other regular keys
471 * @see WANObjectCache::touchCheckKey()
472 * @see WANObjectCache::get()
474 * @param string $key Cache key
475 * @return bool True if the item was purged or not found, false on failure
477 final public function resetCheckKey( $key ) {
478 $key = self
::TIME_KEY_PREFIX
. $key;
479 // Update the local datacenter immediately
480 $ok = $this->cache
->delete( $key );
481 // Publish the purge to all datacenters
482 return $this->relayDelete( $key ) && $ok;
486 * Method to fetch/regenerate cache keys
488 * On cache miss, the key will be set to the callback result via set()
489 * unless the callback returns false. The arguments supplied to it are:
490 * (current value or false, &$ttl, &$setOpts)
491 * The callback function returns the new value given the current
492 * value (false if not present). Preemptive re-caching and $checkKeys
493 * can result in a non-false current value. The TTL of the new value
494 * can be set dynamically by altering $ttl in the callback (by reference).
495 * The $setOpts array can be altered and is given to set() when called;
496 * it is recommended to set the 'since' field to avoid race conditions.
498 * Usually, callbacks ignore the current value, but it can be used
499 * to maintain "most recent X" values that come from time or sequence
500 * based source data, provided that the "as of" id/time is tracked.
502 * Usage of $checkKeys is similar to get() and getMulti(). However,
503 * rather than the caller having to inspect a "current time left"
504 * variable (e.g. $curTTL, $curTTLs), a cache regeneration will be
505 * triggered using the callback.
507 * The simplest way to avoid stampedes for hot keys is to use
508 * the 'lockTSE' option in $opts. If cache purges are needed, also:
509 * - a) Pass $key into $checkKeys
510 * - b) Use touchCheckKey( $key ) instead of delete( $key )
512 * Example usage (typical key):
514 * $catInfo = $cache->getWithSetCallback(
515 * // Key to store the cached value under
516 * wfMemcKey( 'cat-attributes', $catId ),
517 * // Function that derives the new key value
518 * function( $oldValue, &$ttl, array &$setOpts ) {
519 * // Fetch row from the DB
520 * $dbr = wfGetDB( DB_SLAVE );
521 * $row = $dbr->selectRow( ... );
523 * // Set age of the transaction snapshot the data came from
524 * $setOpts = array( 'since' => $dbr->trxTimestamp() );
528 * // Time-to-live (seconds)
533 * Example usage (key that is expensive and hot):
535 * $catConfig = $cache->getWithSetCallback(
536 * // Key to store the cached value under
537 * wfMemcKey( 'site-cat-config' ),
538 * // Function that derives the new key value
539 * function( $oldValue, &$ttl, array &$setOpts ) {
540 * // Fetch row from the DB
541 * $dbr = wfGetDB( DB_SLAVE );
542 * $config = CatConfig::newFromRow( $dbr->selectRow( ... ) );
544 * // Set age of the transaction snapshot the data came from
545 * $setOpts = array( 'since' => $dbr->trxTimestamp() );
549 * // Time-to-live (seconds)
551 * // Calling touchCheckKey() on this key invalidates the cache
552 * wfMemcKey( 'site-cat-config' ),
553 * // Try to only let one datacenter thread manage cache updates at a time
554 * array( 'lockTSE' => 30 )
558 * Example usage (key with dynamic dependencies):
560 * $catState = $cache->getWithSetCallback(
561 * // Key to store the cached value under
562 * wfMemcKey( 'cat-state', $cat->getId() ),
563 * // Function that derives the new key value
564 * function( $oldValue, &$ttl, array &$setOpts ) {
565 * // Determine new value from the DB
566 * $dbr = wfGetDB( DB_SLAVE );
567 * $state = CatState::newFromResults( $dbr->select( ... ) );
569 * // Set age of the transaction snapshot the data came from
570 * $setOpts = array( 'since' => $dbr->trxTimestamp() );
574 * // Time-to-live (seconds)
576 * // The "check" keys that represent things the value depends on;
577 * // Calling touchCheckKey() on any of them invalidates the cache
579 * wfMemcKey( 'sustenance-bowls', $cat->getRoomId() ),
580 * wfMemcKey( 'people-present', $cat->getHouseId() ),
581 * wfMemcKey( 'cat-laws', $cat->getCityId() ),
586 * Example usage (hot key holding most recent 100 events):
588 * $lastCatActions = $cache->getWithSetCallback(
589 * // Key to store the cached value under
590 * wfMemcKey( 'cat-last-actions', 100 ),
591 * // Function that derives the new key value
592 * function( $oldValue, &$ttl, array &$setOpts ) {
593 * $dbr = wfGetDB( DB_SLAVE );
594 * // Start off with the last cached list
595 * $list = $oldValue ?: array();
596 * // Fetch the last 100 relevant rows in descending order;
597 * // only fetch rows newer than $list[0] to reduce scanning
598 * $rows = iterator_to_array( $dbr->select( ... ) );
599 * // Merge them and get the new "last 100" rows
600 * $list = array_slice( array_merge( $new, $list ), 0, 100 );
602 * // Set age of the transaction snapshot the data came from
603 * $setOpts = array( 'since' => $dbr->trxTimestamp() );
607 * // Time-to-live (seconds)
611 * // Try to only let one datacenter thread manage cache updates at a time
612 * array( 'lockTSE' => 30 )
616 * @see WANObjectCache::get()
617 * @see WANObjectCache::set()
619 * @param string $key Cache key
620 * @param callable $callback Value generation function
621 * @param integer $ttl Seconds to live for key updates. Special values are:
622 * - WANObjectCache::TTL_NONE : cache forever
623 * - WANObjectCache::TTL_UNCACHEABLE : do not cache at all
624 * @param array $checkKeys List of "check" keys
625 * @param array $opts Options map:
626 * - lowTTL : consider pre-emptive updates when the current TTL (sec)
627 * of the key is less than this. It becomes more likely
628 * over time, becoming a certainty once the key is expired.
629 * [Default: WANObjectCache::LOW_TTL seconds]
630 * - lockTSE : if the key is tombstoned or expired (by $checkKeys) less
631 * than this many seconds ago, then try to have a single
632 * thread handle cache regeneration at any given time.
633 * Other threads will try to use stale values if possible.
634 * If, on miss, the time since expiration is low, the assumption
635 * is that the key is hot and that a stampede is worth avoiding.
636 * Setting this above WANObjectCache::HOLDOFF_TTL makes no difference.
637 * The higher this is set, the higher the worst-case staleness can be.
638 * Use WANObjectCache::TSE_NONE to disable this logic.
639 * [Default: WANObjectCache::TSE_NONE]
640 * @return mixed Value to use for the key
642 final public function getWithSetCallback(
643 $key, $callback, $ttl, array $checkKeys = array(), array $opts = array()
645 $lowTTL = isset( $opts['lowTTL'] ) ?
$opts['lowTTL'] : min( self
::LOW_TTL
, $ttl );
646 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
648 // Get the current key value
650 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
651 $value = $cValue; // return value
653 // Determine if a regeneration is desired
654 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
658 // A deleted key with a negative TTL left must be tombstoned
659 $isTombstone = ( $curTTL !== null && $value === false );
660 // Assume a key is hot if requested soon after invalidation
661 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
662 // Decide whether a single thread should handle regenerations.
663 // This avoids stampedes when $checkKeys are bumped and when preemptive
664 // renegerations take too long. It also reduces regenerations while $key
665 // is tombstoned. This balances cache freshness with avoiding DB load.
666 $useMutex = ( $isHot ||
( $isTombstone && $lockTSE > 0 ) );
668 $lockAcquired = false;
670 // Acquire a datacenter-local non-blocking lock
671 if ( $this->cache
->lock( $key, 0, self
::LOCK_TTL
) ) {
672 // Lock acquired; this thread should update the key
673 $lockAcquired = true;
674 } elseif ( $value !== false ) {
675 // If it cannot be acquired; then the stale value can be used
678 // Use the stash value for tombstoned keys to reduce regeneration load.
679 // For hot keys, either another thread has the lock or the lock failed;
680 // use the stash value from the last thread that regenerated it.
681 $value = $this->cache
->get( self
::STASH_KEY_PREFIX
. $key );
682 if ( $value !== false ) {
688 if ( !is_callable( $callback ) ) {
689 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
692 // Generate the new value from the callback...
694 $value = call_user_func_array( $callback, array( $cValue, &$ttl, &$setOpts ) );
695 // When delete() is called, writes are write-holed by the tombstone,
696 // so use a special stash key to pass the new value around threads.
697 if ( $useMutex && $value !== false && $ttl >= 0 ) {
698 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
699 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
702 if ( $lockAcquired ) {
703 $this->cache
->unlock( $key );
706 if ( $value !== false && $ttl >= 0 ) {
707 // Update the cache; this will fail if the key is tombstoned
708 $setOpts['lockTSE'] = $lockTSE;
709 $this->set( $key, $value, $ttl, $setOpts );
716 * Get the "last error" registered; clearLastError() should be called manually
717 * @return int ERR_* constant for the "last error" registry
719 final public function getLastError() {
720 if ( $this->lastRelayError
) {
721 // If the cache and the relayer failed, focus on the later.
722 // An update not making it to the relayer means it won't show up
723 // in other DCs (nor will consistent re-hashing see up-to-date values).
724 // On the other hand, if just the cache update failed, then it should
725 // eventually be applied by the relayer.
726 return $this->lastRelayError
;
729 $code = $this->cache
->getLastError();
731 case BagOStuff
::ERR_NONE
:
732 return self
::ERR_NONE
;
733 case BagOStuff
::ERR_NO_RESPONSE
:
734 return self
::ERR_NO_RESPONSE
;
735 case BagOStuff
::ERR_UNREACHABLE
:
736 return self
::ERR_UNREACHABLE
;
738 return self
::ERR_UNEXPECTED
;
743 * Clear the "last error" registry
745 final public function clearLastError() {
746 $this->cache
->clearLastError();
747 $this->lastRelayError
= self
::ERR_NONE
;
751 * Do the actual async bus purge of a key
753 * This must set the key to "PURGED:<UNIX timestamp>"
755 * @param string $key Cache key
756 * @param integer $ttl How long to keep the tombstone [seconds]
757 * @return bool Success
759 protected function relayPurge( $key, $ttl ) {
760 $event = $this->cache
->modifySimpleRelayEvent( array(
763 'val' => 'PURGED:$UNIXTIME$',
764 'ttl' => max( $ttl, 1 ),
765 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
768 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
770 $this->lastRelayError
= self
::ERR_RELAY
;
777 * Do the actual async bus delete of a key
779 * @param string $key Cache key
780 * @return bool Success
782 protected function relayDelete( $key ) {
783 $event = $this->cache
->modifySimpleRelayEvent( array(
788 $ok = $this->relayer
->notify( "{$this->pool}:purge", $event );
790 $this->lastRelayError
= self
::ERR_RELAY
;
797 * Check if a key should be regenerated (using random probability)
799 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
800 * of returning true increases steadily from 0% to 100% as the $curTTL
801 * moves from $lowTTL to 0 seconds. This handles widely varying
802 * levels of cache access traffic.
804 * @param float $curTTL Approximate TTL left on the key if present
805 * @param float $lowTTL Consider a refresh when $curTTL is less than this
808 protected function worthRefresh( $curTTL, $lowTTL ) {
809 if ( $curTTL >= $lowTTL ) {
811 } elseif ( $curTTL <= 0 ) {
815 $chance = ( 1 - $curTTL / $lowTTL );
817 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
821 * Do not use this method outside WANObjectCache
823 * @param mixed $value
824 * @param integer $ttl [0=forever]
827 protected function wrap( $value, $ttl ) {
829 self
::FLD_VERSION
=> self
::VERSION
,
830 self
::FLD_VALUE
=> $value,
831 self
::FLD_TTL
=> $ttl,
832 self
::FLD_TIME
=> microtime( true )
837 * Do not use this method outside WANObjectCache
839 * @param array|string|bool $wrapped
840 * @param float $now Unix Current timestamp (preferrable pre-query)
841 * @return array (mixed; false if absent/invalid, current time left)
843 protected function unwrap( $wrapped, $now ) {
844 // Check if the value is a tombstone
845 $purgeTimestamp = self
::parsePurgeValue( $wrapped );
846 if ( is_float( $purgeTimestamp ) ) {
847 // Purged values should always have a negative current $ttl
848 $curTTL = min( -0.000001, $purgeTimestamp - $now );
849 return array( false, $curTTL );
852 if ( !is_array( $wrapped ) // not found
853 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
854 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
856 return array( false, null );
859 if ( $wrapped[self
::FLD_TTL
] > 0 ) {
860 // Get the approximate time left on the key
861 $age = $now - $wrapped[self
::FLD_TIME
];
862 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
864 // Key had no TTL, so the time left is unbounded
868 return array( $wrapped[self
::FLD_VALUE
], $curTTL );
873 * @param string $prefix
876 protected static function prefixCacheKeys( array $keys, $prefix ) {
878 foreach ( $keys as $key ) {
879 $res[] = $prefix . $key;
886 * @param string $value String like "PURGED:<timestamp>"
887 * @return float|bool UNIX timestamp or false on failure
889 protected static function parsePurgeValue( $value ) {
891 if ( is_string( $value ) &&
892 preg_match( '/^' . self
::PURGE_VAL_PREFIX
. '([^:]+)$/', $value, $m )