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 Purge channel name */
73 protected $purgeChannel;
74 /** @var EventRelayer Bus that handles purge broadcasts */
75 protected $purgeRelayer;
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; // key to cache version number
114 const FLD_VALUE
= 1; // key to the cached value
115 const FLD_TTL
= 2; // key to the original TTL
116 const FLD_TIME
= 3; // key to the cache time
117 const FLD_FLAGS
= 4; // key to the flags bitfield
118 const FLD_HOLDOFF
= 5; // key to any hold-off TTL
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
137 const DEFAULT_PURGE_CHANNEL
= 'wancache-purge';
140 * @param array $params
141 * - cache : BagOStuff object for a persistent cache
142 * - channels : Map of (action => channel string). Actions include "purge".
143 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
144 * - logger : LoggerInterface object
146 public function __construct( array $params ) {
147 $this->cache
= $params['cache'];
148 $this->procCache
= new HashBagOStuff( [ 'maxKeys' => self
::MAX_PC_KEYS
] );
149 $this->purgeChannel
= isset( $params['channels']['purge'] )
150 ?
$params['channels']['purge']
151 : self
::DEFAULT_PURGE_CHANNEL
;
152 $this->purgeRelayer
= isset( $params['relayers']['purge'] )
153 ?
$params['relayers']['purge']
154 : new EventRelayerNull( [] );
155 $this->setLogger( isset( $params['logger'] ) ?
$params['logger'] : new NullLogger() );
158 public function setLogger( LoggerInterface
$logger ) {
159 $this->logger
= $logger;
163 * Get an instance that wraps EmptyBagOStuff
165 * @return WANObjectCache
167 public static function newEmpty() {
169 'cache' => new EmptyBagOStuff(),
171 'relayer' => new EventRelayerNull( [] )
176 * Fetch the value of a key from cache
178 * If supplied, $curTTL is set to the remaining TTL (current time left):
179 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
180 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
181 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
182 * - d) null; if $key does not exist and is not tombstoned
184 * If a key is tombstoned, $curTTL will reflect the time since delete().
186 * The timestamp of $key will be checked against the last-purge timestamp
187 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
188 * initialized to the current timestamp. If any of $checkKeys have a timestamp
189 * greater than that of $key, then $curTTL will reflect how long ago $key
190 * became invalid. Callers can use $curTTL to know when the value is stale.
191 * The $checkKeys parameter allow mass invalidations by updating a single key:
192 * - a) Each "check" key represents "last purged" of some source data
193 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
194 * - c) When the source data that "check" keys represent changes,
195 * the touchCheckKey() method is called on them
197 * Source data entities might exists in a DB that uses snapshot isolation
198 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
199 * isolation can largely be maintained by doing the following:
200 * - a) Calling delete() on entity change *and* creation, before DB commit
201 * - b) Keeping transaction duration shorter than delete() hold-off TTL
203 * However, pre-snapshot values might still be seen if an update was made
204 * in a remote datacenter but the purge from delete() didn't relay yet.
206 * Consider using getWithSetCallback() instead of get() and set() cycles.
207 * That method has cache slam avoiding features for hot/expensive keys.
209 * @param string $key Cache key
210 * @param mixed $curTTL Approximate TTL left on the key if present [returned]
211 * @param array $checkKeys List of "check" keys
212 * @return mixed Value of cache key or false on failure
214 final public function get( $key, &$curTTL = null, array $checkKeys = [] ) {
216 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys );
217 $curTTL = isset( $curTTLs[$key] ) ?
$curTTLs[$key] : null;
219 return isset( $values[$key] ) ?
$values[$key] : false;
223 * Fetch the value of several keys from cache
225 * @see WANObjectCache::get()
227 * @param array $keys List of cache keys
228 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
229 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
230 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
231 * @return array Map of (key => value) for keys that exist
233 final public function getMulti(
234 array $keys, &$curTTLs = [], array $checkKeys = []
239 $vPrefixLen = strlen( self
::VALUE_KEY_PREFIX
);
240 $valueKeys = self
::prefixCacheKeys( $keys, self
::VALUE_KEY_PREFIX
);
242 $checkKeysForAll = [];
243 $checkKeysByKey = [];
245 foreach ( $checkKeys as $i => $keys ) {
246 $prefixed = self
::prefixCacheKeys( (array)$keys, self
::TIME_KEY_PREFIX
);
247 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
248 // Is this check keys for a specific cache key, or for all keys being fetched?
249 if ( is_int( $i ) ) {
250 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
252 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
253 ?
array_merge( $checkKeysByKey[$i], $prefixed )
258 // Fetch all of the raw values
259 $wrappedValues = $this->cache
->getMulti( array_merge( $valueKeys, $checkKeysFlat ) );
260 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
261 $now = microtime( true );
263 // Collect timestamps from all "check" keys
264 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
265 $purgeValuesByKey = [];
266 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
267 $purgeValuesByKey[$cacheKey] =
268 $this->processCheckKeys( $checks, $wrappedValues, $now );
271 // Get the main cache value for each key and validate them
272 foreach ( $valueKeys as $vKey ) {
273 if ( !isset( $wrappedValues[$vKey] ) ) {
274 continue; // not found
277 $key = substr( $vKey, $vPrefixLen ); // unprefix
279 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
280 if ( $value !== false ) {
281 $result[$key] = $value;
283 // Force dependant keys to be invalid for a while after purging
284 // to reduce race conditions involving stale data getting cached
285 $purgeValues = $purgeValuesForAll;
286 if ( isset( $purgeValuesByKey[$key] ) ) {
287 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
289 foreach ( $purgeValues as $purge ) {
290 $safeTimestamp = $purge[self
::FLD_TIME
] +
$purge[self
::FLD_HOLDOFF
];
291 if ( $safeTimestamp >= $wrappedValues[$vKey][self
::FLD_TIME
] ) {
292 // How long ago this value was expired by *this* check key
293 $ago = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
294 // How long ago this value was expired by *any* known check key
295 $curTTL = min( $curTTL, $ago );
299 $curTTLs[$key] = $curTTL;
307 * @param array $timeKeys List of prefixed time check keys
308 * @param array $wrappedValues
310 * @return array List of purge value arrays
312 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
314 foreach ( $timeKeys as $timeKey ) {
315 $purge = isset( $wrappedValues[$timeKey] )
316 ? self
::parsePurgeValue( $wrappedValues[$timeKey] )
318 if ( $purge === false ) {
319 // Key is not set or invalid; regenerate
320 $newVal = $this->makePurgeValue( $now, self
::HOLDOFF_TTL
);
321 $this->cache
->add( $timeKey, $newVal, self
::CHECK_KEY_TTL
);
322 $purge = self
::parsePurgeValue( $newVal );
324 $purgeValues[] = $purge;
330 * Set the value of a key in cache
332 * Simply calling this method when source data changes is not valid because
333 * the changes do not replicate to the other WAN sites. In that case, delete()
334 * should be used instead. This method is intended for use on cache misses.
336 * If the data was read from a snapshot-isolated transactions (e.g. the default
337 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
339 * - b) T2 updates a row, calls delete(), and commits
340 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
341 * - d) T1 reads the row and calls set() due to a cache miss
342 * - e) Stale value is stuck in cache
344 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
348 * $dbr = wfGetDB( DB_SLAVE );
349 * $setOpts = Database::getCacheSetOptions( $dbr );
350 * // Fetch the row from the DB
351 * $row = $dbr->selectRow( ... );
352 * $key = $cache->makeKey( 'building', $buildingId );
353 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
356 * @param string $key Cache key
357 * @param mixed $value
358 * @param integer $ttl Seconds to live. Special values are:
359 * - WANObjectCache::TTL_INDEFINITE: Cache forever
360 * @param array $opts Options map:
361 * - lag : Seconds of slave lag. Typically, this is either the slave lag
362 * before the data was read or, if applicable, the slave lag before
363 * the snapshot-isolated transaction the data was read from started.
365 * - since : UNIX timestamp of the data in $value. Typically, this is either
366 * the current time the data was read or (if applicable) the time when
367 * the snapshot-isolated transaction the data was read from started.
369 * - pending : Whether this data is possibly from an uncommitted write transaction.
370 * Generally, other threads should not see values from the future and
371 * they certainly should not see ones that ended up getting rolled back.
373 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
374 * with this TTL and flag it as stale. This is only useful if the reads for
375 * this key use getWithSetCallback() with "lockTSE" set.
376 * Default: WANObjectCache::TSE_NONE
377 * @return bool Success
379 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
380 $now = microtime( true );
381 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
382 $age = isset( $opts['since'] ) ?
max( 0, $now - $opts['since'] ) : 0;
383 $lag = isset( $opts['lag'] ) ?
$opts['lag'] : 0;
385 // Do not cache potentially uncommitted data as it might get rolled back
386 if ( !empty( $opts['pending'] ) ) {
387 $this->logger
->info( "Rejected set() for $key due to pending writes." );
389 return true; // no-op the write for being unsafe
392 $wrapExtra = []; // additional wrapped value fields
393 // Check if there's a risk of writing stale data after the purge tombstone expired
394 if ( $lag === false ||
( $lag +
$age ) > self
::MAX_READ_LAG
) {
395 // Case A: read lag with "lockTSE"; save but record value as stale
396 if ( $lockTSE >= 0 ) {
397 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
398 $wrapExtra[self
::FLD_FLAGS
] = self
::FLG_STALE
; // mark as stale
399 // Case B: any long-running transaction; ignore this set()
400 } elseif ( $age > self
::MAX_READ_LAG
) {
401 $this->logger
->warning( "Rejected set() for $key due to snapshot lag." );
403 return true; // no-op the write for being unsafe
404 // Case C: high replication lag; lower TTL instead of ignoring all set()s
405 } elseif ( $lag === false ||
$lag > self
::MAX_READ_LAG
) {
406 $ttl = $ttl ?
min( $ttl, self
::TTL_LAGGED
) : self
::TTL_LAGGED
;
407 $this->logger
->warning( "Lowered set() TTL for $key due to replication lag." );
408 // Case D: medium length request with medium replication lag; ignore this set()
410 $this->logger
->warning( "Rejected set() for $key due to high read lag." );
412 return true; // no-op the write for being unsafe
416 // Wrap that value with time/TTL/version metadata
417 $wrapped = $this->wrap( $value, $ttl, $now ) +
$wrapExtra;
419 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
420 return ( is_string( $cWrapped ) )
421 ?
false // key is tombstoned; do nothing
425 return $this->cache
->merge( self
::VALUE_KEY_PREFIX
. $key, $func, $ttl, 1 );
429 * Purge a key from all datacenters
431 * This should only be called when the underlying data (being cached)
432 * changes in a significant way. This deletes the key and starts a hold-off
433 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
434 * This is done to avoid the following race condition:
435 * - a) Some DB data changes and delete() is called on a corresponding key
436 * - b) A request refills the key with a stale value from a lagged DB
437 * - c) The stale value is stuck there until the key is expired/evicted
439 * This is implemented by storing a special "tombstone" value at the cache
440 * key that this class recognizes; get() calls will return false for the key
441 * and any set() calls will refuse to replace tombstone values at the key.
442 * For this to always avoid stale value writes, the following must hold:
443 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
444 * - b) If lag is higher, the DB will have gone into read-only mode already
446 * Note that set() can also be lag-aware and lower the TTL if it's high.
448 * When using potentially long-running ACID transactions, a good pattern is
449 * to use a pre-commit hook to issue the delete. This means that immediately
450 * after commit, callers will see the tombstone in cache in the local datacenter
451 * and in the others upon relay. It also avoids the following race condition:
452 * - a) T1 begins, changes a row, and calls delete()
453 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
454 * - c) T2 starts, reads the row and calls set() due to a cache miss
455 * - d) T1 finally commits
456 * - e) Stale value is stuck in cache
460 * $dbw->begin( __METHOD__ ); // start of request
461 * ... <execute some stuff> ...
462 * // Update the row in the DB
463 * $dbw->update( ... );
464 * $key = $cache->makeKey( 'homes', $homeId );
465 * // Purge the corresponding cache entry just before committing
466 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
467 * $cache->delete( $key );
469 * ... <execute some stuff> ...
470 * $dbw->commit( __METHOD__ ); // end of request
473 * The $ttl parameter can be used when purging values that have not actually changed
474 * recently. For example, a cleanup script to purge cache entries does not really need
475 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
476 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
478 * If called twice on the same key, then the last hold-off TTL takes precedence. For
479 * idempotence, the $ttl should not vary for different delete() calls on the same key.
481 * @param string $key Cache key
482 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
483 * @return bool True if the item was purged or not found, false on failure
485 final public function delete( $key, $ttl = self
::HOLDOFF_TTL
) {
486 $key = self
::VALUE_KEY_PREFIX
. $key;
489 // Update the local datacenter immediately
490 $ok = $this->cache
->delete( $key );
491 // Publish the purge to all datacenters
492 $ok = $this->relayDelete( $key ) && $ok;
494 // Update the local datacenter immediately
495 $ok = $this->cache
->set( $key,
496 $this->makePurgeValue( microtime( true ), self
::HOLDOFF_NONE
),
499 // Publish the purge to all datacenters
500 $ok = $this->relayPurge( $key, $ttl, self
::HOLDOFF_NONE
) && $ok;
507 * Fetch the value of a timestamp "check" key
509 * The key will be *initialized* to the current time if not set,
510 * so only call this method if this behavior is actually desired
512 * The timestamp can be used to check whether a cached value is valid.
513 * Callers should not assume that this returns the same timestamp in
514 * all datacenters due to relay delays.
516 * The level of staleness can roughly be estimated from this key, but
517 * if the key was evicted from cache, such calculations may show the
518 * time since expiry as ~0 seconds.
520 * Note that "check" keys won't collide with other regular keys.
523 * @return float UNIX timestamp of the check key
525 final public function getCheckKeyTime( $key ) {
526 $key = self
::TIME_KEY_PREFIX
. $key;
528 $purge = self
::parsePurgeValue( $this->cache
->get( $key ) );
529 if ( $purge !== false ) {
530 $time = $purge[self
::FLD_TIME
];
532 // Casting assures identical floats for the next getCheckKeyTime() calls
533 $now = (string)microtime( true );
534 $this->cache
->add( $key,
535 $this->makePurgeValue( $now, self
::HOLDOFF_TTL
),
545 * Purge a "check" key from all datacenters, invalidating keys that use it
547 * This should only be called when the underlying data (being cached)
548 * changes in a significant way, and it is impractical to call delete()
549 * on all keys that should be changed. When get() is called on those
550 * keys, the relevant "check" keys must be supplied for this to work.
552 * The "check" key essentially represents a last-modified field.
553 * When touched, keys using it via get(), getMulti(), or getWithSetCallback()
554 * will be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
555 * by those methods to avoid race conditions where dependent keys get updated
556 * with stale values (e.g. from a DB slave).
558 * This is typically useful for keys with hardcoded names or in some cases
559 * dynamically generated names where a low number of combinations exist.
560 * When a few important keys get a large number of hits, a high cache
561 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
562 * method is less appropriate in such cases since the "time since expiry"
563 * cannot be inferred.
565 * Note that "check" keys won't collide with other regular keys.
567 * @see WANObjectCache::get()
568 * @see WANObjectCache::getWithSetCallback()
569 * @see WANObjectCache::resetCheckKey()
571 * @param string $key Cache key
572 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
573 * @return bool True if the item was purged or not found, false on failure
575 final public function touchCheckKey( $key, $holdoff = self
::HOLDOFF_TTL
) {
576 $key = self
::TIME_KEY_PREFIX
. $key;
577 // Update the local datacenter immediately
578 $ok = $this->cache
->set( $key,
579 $this->makePurgeValue( microtime( true ), $holdoff ),
582 // Publish the purge to all datacenters
583 return $this->relayPurge( $key, self
::CHECK_KEY_TTL
, $holdoff ) && $ok;
587 * Delete a "check" key from all datacenters, invalidating keys that use it
589 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
590 * or getWithSetCallback() will be invalidated. The differences are:
591 * - a) The timestamp will be deleted from all caches and lazily
592 * re-initialized when accessed (rather than set everywhere)
593 * - b) Thus, dependent keys will be known to be invalid, but not
594 * for how long (they are treated as "just" purged), which
595 * effects any lockTSE logic in getWithSetCallback()
597 * The advantage is that this does not place high TTL keys on every cache
598 * server, making it better for code that will cache many different keys
599 * and either does not use lockTSE or uses a low enough TTL anyway.
601 * This is typically useful for keys with dynamically generated names
602 * where a high number of combinations exist.
604 * Note that "check" keys won't collide with other regular keys.
606 * @see WANObjectCache::get()
607 * @see WANObjectCache::getWithSetCallback()
608 * @see WANObjectCache::touchCheckKey()
610 * @param string $key Cache key
611 * @return bool True if the item was purged or not found, false on failure
613 final public function resetCheckKey( $key ) {
614 $key = self
::TIME_KEY_PREFIX
. $key;
615 // Update the local datacenter immediately
616 $ok = $this->cache
->delete( $key );
617 // Publish the purge to all datacenters
618 return $this->relayDelete( $key ) && $ok;
622 * Method to fetch/regenerate cache keys
624 * On cache miss, the key will be set to the callback result via set()
625 * (unless the callback returns false) and that result will be returned.
626 * The arguments supplied to the callback are:
627 * - $oldValue : current cache value or false if not present
628 * - &$ttl : a reference to the TTL which can be altered
629 * - &$setOpts : a reference to options for set() which can be altered
631 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
632 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
633 * value, but it can be used to maintain "most recent X" values that come from time or
634 * sequence based source data, provided that the "as of" id/time is tracked. Note that
635 * preemptive regeneration and $checkKeys can result in a non-false current value.
637 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
638 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
639 * regeneration will automatically be triggered using the callback.
641 * The simplest way to avoid stampedes for hot keys is to use
642 * the 'lockTSE' option in $opts. If cache purges are needed, also:
643 * - a) Pass $key into $checkKeys
644 * - b) Use touchCheckKey( $key ) instead of delete( $key )
646 * Example usage (typical key):
648 * $catInfo = $cache->getWithSetCallback(
649 * // Key to store the cached value under
650 * $cache->makeKey( 'cat-attributes', $catId ),
651 * // Time-to-live (in seconds)
652 * $cache::TTL_MINUTE,
653 * // Function that derives the new key value
654 * function ( $oldValue, &$ttl, array &$setOpts ) {
655 * $dbr = wfGetDB( DB_SLAVE );
656 * // Account for any snapshot/slave lag
657 * $setOpts += Database::getCacheSetOptions( $dbr );
659 * return $dbr->selectRow( ... );
664 * Example usage (key that is expensive and hot):
666 * $catConfig = $cache->getWithSetCallback(
667 * // Key to store the cached value under
668 * $cache->makeKey( 'site-cat-config' ),
669 * // Time-to-live (in seconds)
671 * // Function that derives the new key value
672 * function ( $oldValue, &$ttl, array &$setOpts ) {
673 * $dbr = wfGetDB( DB_SLAVE );
674 * // Account for any snapshot/slave lag
675 * $setOpts += Database::getCacheSetOptions( $dbr );
677 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
680 * // Calling touchCheckKey() on this key invalidates the cache
681 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
682 * // Try to only let one datacenter thread manage cache updates at a time
688 * Example usage (key with dynamic dependencies):
690 * $catState = $cache->getWithSetCallback(
691 * // Key to store the cached value under
692 * $cache->makeKey( 'cat-state', $cat->getId() ),
693 * // Time-to-live (seconds)
695 * // Function that derives the new key value
696 * function ( $oldValue, &$ttl, array &$setOpts ) {
697 * // Determine new value from the DB
698 * $dbr = wfGetDB( DB_SLAVE );
699 * // Account for any snapshot/slave lag
700 * $setOpts += Database::getCacheSetOptions( $dbr );
702 * return CatState::newFromResults( $dbr->select( ... ) );
705 * // The "check" keys that represent things the value depends on;
706 * // Calling touchCheckKey() on any of them invalidates the cache
708 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
709 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
710 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
716 * Example usage (hot key holding most recent 100 events):
718 * $lastCatActions = $cache->getWithSetCallback(
719 * // Key to store the cached value under
720 * $cache->makeKey( 'cat-last-actions', 100 ),
721 * // Time-to-live (in seconds)
723 * // Function that derives the new key value
724 * function ( $oldValue, &$ttl, array &$setOpts ) {
725 * $dbr = wfGetDB( DB_SLAVE );
726 * // Account for any snapshot/slave lag
727 * $setOpts += Database::getCacheSetOptions( $dbr );
729 * // Start off with the last cached list
730 * $list = $oldValue ?: [];
731 * // Fetch the last 100 relevant rows in descending order;
732 * // only fetch rows newer than $list[0] to reduce scanning
733 * $rows = iterator_to_array( $dbr->select( ... ) );
734 * // Merge them and get the new "last 100" rows
735 * return array_slice( array_merge( $new, $list ), 0, 100 );
737 * // Try to only let one datacenter thread manage cache updates at a time
738 * [ 'lockTSE' => 30 ]
742 * @see WANObjectCache::get()
743 * @see WANObjectCache::set()
745 * @param string $key Cache key
746 * @param integer $ttl Seconds to live for key updates. Special values are:
747 * - WANObjectCache::TTL_INDEFINITE: Cache forever
748 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
749 * @param callable $callback Value generation function
750 * @param array $opts Options map:
751 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
752 * touchCheckKey() or resetCheckKey() is called on any of these keys.
753 * - lowTTL: Consider pre-emptive updates when the current TTL (sec) of the key is less than
754 * this. It becomes more likely over time, becoming a certainty once the key is expired.
755 * Default: WANObjectCache::LOW_TTL seconds.
756 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
757 * ago, then try to have a single thread handle cache regeneration at any given time.
758 * Other threads will try to use stale values if possible. If, on miss, the time since
759 * expiration is low, the assumption is that the key is hot and that a stampede is worth
760 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
761 * higher this is set, the higher the worst-case staleness can be.
762 * Use WANObjectCache::TSE_NONE to disable this logic.
763 * Default: WANObjectCache::TSE_NONE.
764 * - pcTTL : process cache the value in this PHP instance with this TTL. This avoids
765 * network I/O when a key is read several times. This will not cache if the callback
766 * returns false however. Note that any purges will not be seen while process cached;
767 * since the callback should use slave DBs and they may be lagged or have snapshot
768 * isolation anyway, this should not typically matter.
769 * Default: WANObjectCache::TTL_UNCACHEABLE.
770 * @return mixed Value to use for the key
772 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
773 $pcTTL = isset( $opts['pcTTL'] ) ?
$opts['pcTTL'] : self
::TTL_UNCACHEABLE
;
775 // Try the process cache if enabled
776 $value = ( $pcTTL >= 0 ) ?
$this->procCache
->get( $key ) : false;
778 if ( $value === false ) {
779 // Fetch the value over the network
780 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
781 // Update the process cache if enabled
782 if ( $pcTTL >= 0 && $value !== false ) {
783 $this->procCache
->set( $key, $value, $pcTTL );
791 * Do the actual I/O for getWithSetCallback() when needed
793 * @see WANObjectCache::getWithSetCallback()
796 * @param integer $ttl
797 * @param callback $callback
801 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts ) {
802 $lowTTL = isset( $opts['lowTTL'] ) ?
$opts['lowTTL'] : min( self
::LOW_TTL
, $ttl );
803 $lockTSE = isset( $opts['lockTSE'] ) ?
$opts['lockTSE'] : self
::TSE_NONE
;
804 $checkKeys = isset( $opts['checkKeys'] ) ?
$opts['checkKeys'] : [];
806 // Get the current key value
808 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
809 $value = $cValue; // return value
811 // Determine if a regeneration is desired
812 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
816 // A deleted key with a negative TTL left must be tombstoned
817 $isTombstone = ( $curTTL !== null && $value === false );
818 // Assume a key is hot if requested soon after invalidation
819 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
820 // Decide whether a single thread should handle regenerations.
821 // This avoids stampedes when $checkKeys are bumped and when preemptive
822 // renegerations take too long. It also reduces regenerations while $key
823 // is tombstoned. This balances cache freshness with avoiding DB load.
824 $useMutex = ( $isHot ||
( $isTombstone && $lockTSE > 0 ) );
826 $lockAcquired = false;
828 // Acquire a datacenter-local non-blocking lock
829 if ( $this->cache
->lock( $key, 0, self
::LOCK_TTL
) ) {
830 // Lock acquired; this thread should update the key
831 $lockAcquired = true;
832 } elseif ( $value !== false ) {
833 // If it cannot be acquired; then the stale value can be used
836 // Use the stash value for tombstoned keys to reduce regeneration load.
837 // For hot keys, either another thread has the lock or the lock failed;
838 // use the stash value from the last thread that regenerated it.
839 $value = $this->cache
->get( self
::STASH_KEY_PREFIX
. $key );
840 if ( $value !== false ) {
846 if ( !is_callable( $callback ) ) {
847 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
850 // Generate the new value from the callback...
852 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts ] );
853 // When delete() is called, writes are write-holed by the tombstone,
854 // so use a special stash key to pass the new value around threads.
855 if ( $useMutex && $value !== false && $ttl >= 0 ) {
856 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
857 $this->cache
->set( self
::STASH_KEY_PREFIX
. $key, $value, $tempTTL );
860 if ( $lockAcquired ) {
861 $this->cache
->unlock( $key );
864 if ( $value !== false && $ttl >= 0 ) {
865 // Update the cache; this will fail if the key is tombstoned
866 $setOpts['lockTSE'] = $lockTSE;
867 $this->set( $key, $value, $ttl, $setOpts );
874 * @see BagOStuff::makeKey()
875 * @param string ... Key component
879 public function makeKey() {
880 return call_user_func_array( [ $this->cache
, __FUNCTION__
], func_get_args() );
884 * @see BagOStuff::makeGlobalKey()
885 * @param string ... Key component
889 public function makeGlobalKey() {
890 return call_user_func_array( [ $this->cache
, __FUNCTION__
], func_get_args() );
894 * Get the "last error" registered; clearLastError() should be called manually
895 * @return int ERR_* constant for the "last error" registry
897 final public function getLastError() {
898 if ( $this->lastRelayError
) {
899 // If the cache and the relayer failed, focus on the later.
900 // An update not making it to the relayer means it won't show up
901 // in other DCs (nor will consistent re-hashing see up-to-date values).
902 // On the other hand, if just the cache update failed, then it should
903 // eventually be applied by the relayer.
904 return $this->lastRelayError
;
907 $code = $this->cache
->getLastError();
909 case BagOStuff
::ERR_NONE
:
910 return self
::ERR_NONE
;
911 case BagOStuff
::ERR_NO_RESPONSE
:
912 return self
::ERR_NO_RESPONSE
;
913 case BagOStuff
::ERR_UNREACHABLE
:
914 return self
::ERR_UNREACHABLE
;
916 return self
::ERR_UNEXPECTED
;
921 * Clear the "last error" registry
923 final public function clearLastError() {
924 $this->cache
->clearLastError();
925 $this->lastRelayError
= self
::ERR_NONE
;
929 * Clear the in-process caches; useful for testing
933 public function clearProcessCache() {
934 $this->procCache
->clear();
938 * Do the actual async bus purge of a key
940 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
942 * @param string $key Cache key
943 * @param integer $ttl How long to keep the tombstone [seconds]
944 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
945 * @return bool Success
947 protected function relayPurge( $key, $ttl, $holdoff ) {
948 $event = $this->cache
->modifySimpleRelayEvent( [
951 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
952 'ttl' => max( $ttl, 1 ),
953 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
956 $ok = $this->purgeRelayer
->notify( $this->purgeChannel
, $event );
958 $this->lastRelayError
= self
::ERR_RELAY
;
965 * Do the actual async bus delete of a key
967 * @param string $key Cache key
968 * @return bool Success
970 protected function relayDelete( $key ) {
971 $event = $this->cache
->modifySimpleRelayEvent( [
976 $ok = $this->purgeRelayer
->notify( $this->purgeChannel
, $event );
978 $this->lastRelayError
= self
::ERR_RELAY
;
985 * Check if a key should be regenerated (using random probability)
987 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
988 * of returning true increases steadily from 0% to 100% as the $curTTL
989 * moves from $lowTTL to 0 seconds. This handles widely varying
990 * levels of cache access traffic.
992 * @param float $curTTL Approximate TTL left on the key if present
993 * @param float $lowTTL Consider a refresh when $curTTL is less than this
996 protected function worthRefresh( $curTTL, $lowTTL ) {
997 if ( $curTTL >= $lowTTL ) {
999 } elseif ( $curTTL <= 0 ) {
1003 $chance = ( 1 - $curTTL / $lowTTL );
1005 return mt_rand( 1, 1e9
) <= 1e9
* $chance;
1009 * Do not use this method outside WANObjectCache
1011 * @param mixed $value
1012 * @param integer $ttl [0=forever]
1013 * @param float $now Unix Current timestamp just before calling set()
1016 protected function wrap( $value, $ttl, $now ) {
1018 self
::FLD_VERSION
=> self
::VERSION
,
1019 self
::FLD_VALUE
=> $value,
1020 self
::FLD_TTL
=> $ttl,
1021 self
::FLD_TIME
=> $now
1026 * Do not use this method outside WANObjectCache
1028 * @param array|string|bool $wrapped
1029 * @param float $now Unix Current timestamp (preferrably pre-query)
1030 * @return array (mixed; false if absent/invalid, current time left)
1032 protected function unwrap( $wrapped, $now ) {
1033 // Check if the value is a tombstone
1034 $purge = self
::parsePurgeValue( $wrapped );
1035 if ( $purge !== false ) {
1036 // Purged values should always have a negative current $ttl
1037 $curTTL = min( $purge[self
::FLD_TIME
] - $now, self
::TINY_NEGATIVE
);
1038 return [ false, $curTTL ];
1041 if ( !is_array( $wrapped ) // not found
1042 ||
!isset( $wrapped[self
::FLD_VERSION
] ) // wrong format
1043 ||
$wrapped[self
::FLD_VERSION
] !== self
::VERSION
// wrong version
1045 return [ false, null ];
1048 $flags = isset( $wrapped[self
::FLD_FLAGS
] ) ?
$wrapped[self
::FLD_FLAGS
] : 0;
1049 if ( ( $flags & self
::FLG_STALE
) == self
::FLG_STALE
) {
1050 // Treat as expired, with the cache time as the expiration
1051 $age = $now - $wrapped[self
::FLD_TIME
];
1052 $curTTL = min( -$age, self
::TINY_NEGATIVE
);
1053 } elseif ( $wrapped[self
::FLD_TTL
] > 0 ) {
1054 // Get the approximate time left on the key
1055 $age = $now - $wrapped[self
::FLD_TIME
];
1056 $curTTL = max( $wrapped[self
::FLD_TTL
] - $age, 0.0 );
1058 // Key had no TTL, so the time left is unbounded
1062 return [ $wrapped[self
::FLD_VALUE
], $curTTL ];
1066 * @param array $keys
1067 * @param string $prefix
1070 protected static function prefixCacheKeys( array $keys, $prefix ) {
1072 foreach ( $keys as $key ) {
1073 $res[] = $prefix . $key;
1080 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1081 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1082 * or false if value isn't a valid purge value
1084 protected static function parsePurgeValue( $value ) {
1085 if ( !is_string( $value ) ) {
1088 $segments = explode( ':', $value, 3 );
1089 if ( !isset( $segments[0] ) ||
!isset( $segments[1] )
1090 ||
"{$segments[0]}:" !== self
::PURGE_VAL_PREFIX
1094 if ( !isset( $segments[2] ) ) {
1095 // Back-compat with old purge values without holdoff
1096 $segments[2] = self
::HOLDOFF_TTL
;
1099 self
::FLD_TIME
=> (float)$segments[1],
1100 self
::FLD_HOLDOFF
=> (int)$segments[2],
1105 * @param float $timestamp
1106 * @param int $holdoff In seconds
1107 * @return string Wrapped purge value
1109 protected function makePurgeValue( $timestamp, $holdoff ) {
1110 return self
::PURGE_VAL_PREFIX
. (float)$timestamp . ':' . (int)$holdoff;