Document WAN cache FLD_* constants
[lhc/web/wiklou.git] / includes / libs / objectcache / WANObjectCache.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 * @ingroup Cache
20 * @author Aaron Schulz
21 */
22
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26
27 /**
28 * Multi-datacenter aware caching interface
29 *
30 * All operations go to the local datacenter cache, except for delete(),
31 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
32 *
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
43 *
44 * The simplest purge method is delete().
45 *
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.
49 *
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.
56 *
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
63 *
64 * @ingroup Cache
65 * @since 1.26
66 */
67 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
68 /** @var BagOStuff The local datacenter cache */
69 protected $cache;
70 /** @var HashBagOStuff Script instance PHP cache */
71 protected $procCache;
72 /** @var string Purge channel name */
73 protected $purgeChannel;
74 /** @var EventRelayer Bus that handles purge broadcasts */
75 protected $purgeRelayer;
76 /** @var LoggerInterface */
77 protected $logger;
78
79 /** @var int ERR_* constant for the "last error" registry */
80 protected $lastRelayError = self::ERR_NONE;
81
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
88
89 /** Seconds to keep dependency purge keys around */
90 const CHECK_KEY_TTL = self::TTL_YEAR;
91 /** Seconds to keep lock keys around */
92 const LOCK_TTL = 10;
93 /** Default remaining TTL at which to consider pre-emptive regeneration */
94 const LOW_TTL = 30;
95 /** Default time-since-expiry on a miss that makes a key "hot" */
96 const LOCK_TSE = 1;
97
98 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
99 const TTL_UNCACHEABLE = -1;
100 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
101 const TSE_NONE = -1;
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;
106
107 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
108 const TINY_NEGATIVE = -0.000001;
109
110 /** Cache format version number */
111 const VERSION = 1;
112
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
119
120 /** @var integer Treat this value as expired-on-arrival */
121 const FLG_STALE = 1;
122
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
128
129 const VALUE_KEY_PREFIX = 'WANCache:v:';
130 const STASH_KEY_PREFIX = 'WANCache:s:';
131 const TIME_KEY_PREFIX = 'WANCache:t:';
132
133 const PURGE_VAL_PREFIX = 'PURGED:';
134
135 const MAX_PC_KEYS = 1000; // max keys to keep in process cache
136
137 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
138
139 /**
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
145 */
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() );
156 }
157
158 public function setLogger( LoggerInterface $logger ) {
159 $this->logger = $logger;
160 }
161
162 /**
163 * Get an instance that wraps EmptyBagOStuff
164 *
165 * @return WANObjectCache
166 */
167 public static function newEmpty() {
168 return new self( [
169 'cache' => new EmptyBagOStuff(),
170 'pool' => 'empty',
171 'relayer' => new EventRelayerNull( [] )
172 ] );
173 }
174
175 /**
176 * Fetch the value of a key from cache
177 *
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
183 *
184 * If a key is tombstoned, $curTTL will reflect the time since delete().
185 *
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
196 *
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
202 *
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.
205 *
206 * Consider using getWithSetCallback() instead of get() and set() cycles.
207 * That method has cache slam avoiding features for hot/expensive keys.
208 *
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
213 */
214 final public function get( $key, &$curTTL = null, array $checkKeys = [] ) {
215 $curTTLs = [];
216 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys );
217 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
218
219 return isset( $values[$key] ) ? $values[$key] : false;
220 }
221
222 /**
223 * Fetch the value of several keys from cache
224 *
225 * @see WANObjectCache::get()
226 *
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
232 */
233 final public function getMulti(
234 array $keys, &$curTTLs = [], array $checkKeys = []
235 ) {
236 $result = [];
237 $curTTLs = [];
238
239 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
240 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
241
242 $checkKeysForAll = [];
243 $checkKeysByKey = [];
244 $checkKeysFlat = [];
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 );
251 } else {
252 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
253 ? array_merge( $checkKeysByKey[$i], $prefixed )
254 : $prefixed;
255 }
256 }
257
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 );
262
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 );
269 }
270
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
275 }
276
277 $key = substr( $vKey, $vPrefixLen ); // unprefix
278
279 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
280 if ( $value !== false ) {
281 $result[$key] = $value;
282
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] );
288 }
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 );
296 }
297 }
298 }
299 $curTTLs[$key] = $curTTL;
300 }
301
302 return $result;
303 }
304
305 /**
306 * @since 1.27
307 * @param array $timeKeys List of prefixed time check keys
308 * @param array $wrappedValues
309 * @param float $now
310 * @return array List of purge value arrays
311 */
312 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
313 $purgeValues = [];
314 foreach ( $timeKeys as $timeKey ) {
315 $purge = isset( $wrappedValues[$timeKey] )
316 ? self::parsePurgeValue( $wrappedValues[$timeKey] )
317 : false;
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 );
323 }
324 $purgeValues[] = $purge;
325 }
326 return $purgeValues;
327 }
328
329 /**
330 * Set the value of a key in cache
331 *
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.
335 *
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:
338 * - a) T1 starts
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
343 *
344 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
345 *
346 * Example usage:
347 * @code
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 );
354 * @endcode
355 *
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.
364 * Default: 0 seconds
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.
368 * Default: 0 seconds
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.
372 * Default: false
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
378 */
379 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
380 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
381 $age = isset( $opts['since'] ) ? max( 0, microtime( true ) - $opts['since'] ) : 0;
382 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
383
384 // Do not cache potentially uncommitted data as it might get rolled back
385 if ( !empty( $opts['pending'] ) ) {
386 $this->logger->info( "Rejected set() for $key due to pending writes." );
387
388 return true; // no-op the write for being unsafe
389 }
390
391 $wrapExtra = []; // additional wrapped value fields
392 // Check if there's a risk of writing stale data after the purge tombstone expired
393 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
394 // Case A: read lag with "lockTSE"; save but record value as stale
395 if ( $lockTSE >= 0 ) {
396 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
397 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
398 // Case B: any long-running transaction; ignore this set()
399 } elseif ( $age > self::MAX_READ_LAG ) {
400 $this->logger->warning( "Rejected set() for $key due to snapshot lag." );
401
402 return true; // no-op the write for being unsafe
403 // Case C: high replication lag; lower TTL instead of ignoring all set()s
404 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
405 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
406 $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
407 // Case D: medium length request with medium replication lag; ignore this set()
408 } else {
409 $this->logger->warning( "Rejected set() for $key due to high read lag." );
410
411 return true; // no-op the write for being unsafe
412 }
413 }
414
415 // Wrap that value with time/TTL/version metadata
416 $wrapped = $this->wrap( $value, $ttl ) + $wrapExtra;
417
418 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
419 return ( is_string( $cWrapped ) )
420 ? false // key is tombstoned; do nothing
421 : $wrapped;
422 };
423
424 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl, 1 );
425 }
426
427 /**
428 * Purge a key from all datacenters
429 *
430 * This should only be called when the underlying data (being cached)
431 * changes in a significant way. This deletes the key and starts a hold-off
432 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
433 * This is done to avoid the following race condition:
434 * - a) Some DB data changes and delete() is called on a corresponding key
435 * - b) A request refills the key with a stale value from a lagged DB
436 * - c) The stale value is stuck there until the key is expired/evicted
437 *
438 * This is implemented by storing a special "tombstone" value at the cache
439 * key that this class recognizes; get() calls will return false for the key
440 * and any set() calls will refuse to replace tombstone values at the key.
441 * For this to always avoid stale value writes, the following must hold:
442 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
443 * - b) If lag is higher, the DB will have gone into read-only mode already
444 *
445 * Note that set() can also be lag-aware and lower the TTL if it's high.
446 *
447 * When using potentially long-running ACID transactions, a good pattern is
448 * to use a pre-commit hook to issue the delete. This means that immediately
449 * after commit, callers will see the tombstone in cache in the local datacenter
450 * and in the others upon relay. It also avoids the following race condition:
451 * - a) T1 begins, changes a row, and calls delete()
452 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
453 * - c) T2 starts, reads the row and calls set() due to a cache miss
454 * - d) T1 finally commits
455 * - e) Stale value is stuck in cache
456 *
457 * Example usage:
458 * @code
459 * $dbw->begin( __METHOD__ ); // start of request
460 * ... <execute some stuff> ...
461 * // Update the row in the DB
462 * $dbw->update( ... );
463 * $key = $cache->makeKey( 'homes', $homeId );
464 * // Purge the corresponding cache entry just before committing
465 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
466 * $cache->delete( $key );
467 * } );
468 * ... <execute some stuff> ...
469 * $dbw->commit( __METHOD__ ); // end of request
470 * @endcode
471 *
472 * The $ttl parameter can be used when purging values that have not actually changed
473 * recently. For example, a cleanup script to purge cache entries does not really need
474 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
475 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
476 *
477 * If called twice on the same key, then the last hold-off TTL takes precedence. For
478 * idempotence, the $ttl should not vary for different delete() calls on the same key.
479 *
480 * @param string $key Cache key
481 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
482 * @return bool True if the item was purged or not found, false on failure
483 */
484 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
485 $key = self::VALUE_KEY_PREFIX . $key;
486
487 if ( $ttl <= 0 ) {
488 // Update the local datacenter immediately
489 $ok = $this->cache->delete( $key );
490 // Publish the purge to all datacenters
491 $ok = $this->relayDelete( $key ) && $ok;
492 } else {
493 // Update the local datacenter immediately
494 $ok = $this->cache->set( $key,
495 $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
496 $ttl
497 );
498 // Publish the purge to all datacenters
499 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE ) && $ok;
500 }
501
502 return $ok;
503 }
504
505 /**
506 * Fetch the value of a timestamp "check" key
507 *
508 * The key will be *initialized* to the current time if not set,
509 * so only call this method if this behavior is actually desired
510 *
511 * The timestamp can be used to check whether a cached value is valid.
512 * Callers should not assume that this returns the same timestamp in
513 * all datacenters due to relay delays.
514 *
515 * The level of staleness can roughly be estimated from this key, but
516 * if the key was evicted from cache, such calculations may show the
517 * time since expiry as ~0 seconds.
518 *
519 * Note that "check" keys won't collide with other regular keys.
520 *
521 * @param string $key
522 * @return float UNIX timestamp of the check key
523 */
524 final public function getCheckKeyTime( $key ) {
525 $key = self::TIME_KEY_PREFIX . $key;
526
527 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
528 if ( $purge !== false ) {
529 $time = $purge[self::FLD_TIME];
530 } else {
531 // Casting assures identical floats for the next getCheckKeyTime() calls
532 $now = (string)microtime( true );
533 $this->cache->add( $key,
534 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
535 self::CHECK_KEY_TTL
536 );
537 $time = (float)$now;
538 }
539
540 return $time;
541 }
542
543 /**
544 * Purge a "check" key from all datacenters, invalidating keys that use it
545 *
546 * This should only be called when the underlying data (being cached)
547 * changes in a significant way, and it is impractical to call delete()
548 * on all keys that should be changed. When get() is called on those
549 * keys, the relevant "check" keys must be supplied for this to work.
550 *
551 * The "check" key essentially represents a last-modified field.
552 * When touched, keys using it via get(), getMulti(), or getWithSetCallback()
553 * will be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
554 * by those methods to avoid race conditions where dependent keys get updated
555 * with stale values (e.g. from a DB slave).
556 *
557 * This is typically useful for keys with hardcoded names or in some cases
558 * dynamically generated names where a low number of combinations exist.
559 * When a few important keys get a large number of hits, a high cache
560 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
561 * method is less appropriate in such cases since the "time since expiry"
562 * cannot be inferred.
563 *
564 * Note that "check" keys won't collide with other regular keys.
565 *
566 * @see WANObjectCache::get()
567 * @see WANObjectCache::getWithSetCallback()
568 * @see WANObjectCache::resetCheckKey()
569 *
570 * @param string $key Cache key
571 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
572 * @return bool True if the item was purged or not found, false on failure
573 */
574 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
575 $key = self::TIME_KEY_PREFIX . $key;
576 // Update the local datacenter immediately
577 $ok = $this->cache->set( $key,
578 $this->makePurgeValue( microtime( true ), $holdoff ),
579 self::CHECK_KEY_TTL
580 );
581 // Publish the purge to all datacenters
582 return $this->relayPurge( $key, self::CHECK_KEY_TTL, $holdoff ) && $ok;
583 }
584
585 /**
586 * Delete a "check" key from all datacenters, invalidating keys that use it
587 *
588 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
589 * or getWithSetCallback() will be invalidated. The differences are:
590 * - a) The timestamp will be deleted from all caches and lazily
591 * re-initialized when accessed (rather than set everywhere)
592 * - b) Thus, dependent keys will be known to be invalid, but not
593 * for how long (they are treated as "just" purged), which
594 * effects any lockTSE logic in getWithSetCallback()
595 *
596 * The advantage is that this does not place high TTL keys on every cache
597 * server, making it better for code that will cache many different keys
598 * and either does not use lockTSE or uses a low enough TTL anyway.
599 *
600 * This is typically useful for keys with dynamically generated names
601 * where a high number of combinations exist.
602 *
603 * Note that "check" keys won't collide with other regular keys.
604 *
605 * @see WANObjectCache::get()
606 * @see WANObjectCache::getWithSetCallback()
607 * @see WANObjectCache::touchCheckKey()
608 *
609 * @param string $key Cache key
610 * @return bool True if the item was purged or not found, false on failure
611 */
612 final public function resetCheckKey( $key ) {
613 $key = self::TIME_KEY_PREFIX . $key;
614 // Update the local datacenter immediately
615 $ok = $this->cache->delete( $key );
616 // Publish the purge to all datacenters
617 return $this->relayDelete( $key ) && $ok;
618 }
619
620 /**
621 * Method to fetch/regenerate cache keys
622 *
623 * On cache miss, the key will be set to the callback result via set()
624 * (unless the callback returns false) and that result will be returned.
625 * The arguments supplied to the callback are:
626 * - $oldValue : current cache value or false if not present
627 * - &$ttl : a reference to the TTL which can be altered
628 * - &$setOpts : a reference to options for set() which can be altered
629 *
630 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
631 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
632 * value, but it can be used to maintain "most recent X" values that come from time or
633 * sequence based source data, provided that the "as of" id/time is tracked. Note that
634 * preemptive regeneration and $checkKeys can result in a non-false current value.
635 *
636 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
637 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
638 * regeneration will automatically be triggered using the callback.
639 *
640 * The simplest way to avoid stampedes for hot keys is to use
641 * the 'lockTSE' option in $opts. If cache purges are needed, also:
642 * - a) Pass $key into $checkKeys
643 * - b) Use touchCheckKey( $key ) instead of delete( $key )
644 *
645 * Example usage (typical key):
646 * @code
647 * $catInfo = $cache->getWithSetCallback(
648 * // Key to store the cached value under
649 * $cache->makeKey( 'cat-attributes', $catId ),
650 * // Time-to-live (in seconds)
651 * $cache::TTL_MINUTE,
652 * // Function that derives the new key value
653 * function ( $oldValue, &$ttl, array &$setOpts ) {
654 * $dbr = wfGetDB( DB_SLAVE );
655 * // Account for any snapshot/slave lag
656 * $setOpts += Database::getCacheSetOptions( $dbr );
657 *
658 * return $dbr->selectRow( ... );
659 * }
660 * );
661 * @endcode
662 *
663 * Example usage (key that is expensive and hot):
664 * @code
665 * $catConfig = $cache->getWithSetCallback(
666 * // Key to store the cached value under
667 * $cache->makeKey( 'site-cat-config' ),
668 * // Time-to-live (in seconds)
669 * $cache::TTL_DAY,
670 * // Function that derives the new key value
671 * function ( $oldValue, &$ttl, array &$setOpts ) {
672 * $dbr = wfGetDB( DB_SLAVE );
673 * // Account for any snapshot/slave lag
674 * $setOpts += Database::getCacheSetOptions( $dbr );
675 *
676 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
677 * },
678 * [
679 * // Calling touchCheckKey() on this key invalidates the cache
680 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
681 * // Try to only let one datacenter thread manage cache updates at a time
682 * 'lockTSE' => 30
683 * ]
684 * );
685 * @endcode
686 *
687 * Example usage (key with dynamic dependencies):
688 * @code
689 * $catState = $cache->getWithSetCallback(
690 * // Key to store the cached value under
691 * $cache->makeKey( 'cat-state', $cat->getId() ),
692 * // Time-to-live (seconds)
693 * $cache::TTL_HOUR,
694 * // Function that derives the new key value
695 * function ( $oldValue, &$ttl, array &$setOpts ) {
696 * // Determine new value from the DB
697 * $dbr = wfGetDB( DB_SLAVE );
698 * // Account for any snapshot/slave lag
699 * $setOpts += Database::getCacheSetOptions( $dbr );
700 *
701 * return CatState::newFromResults( $dbr->select( ... ) );
702 * },
703 * [
704 * // The "check" keys that represent things the value depends on;
705 * // Calling touchCheckKey() on any of them invalidates the cache
706 * 'checkKeys' => [
707 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
708 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
709 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
710 * ]
711 * ]
712 * );
713 * @endcode
714 *
715 * Example usage (hot key holding most recent 100 events):
716 * @code
717 * $lastCatActions = $cache->getWithSetCallback(
718 * // Key to store the cached value under
719 * $cache->makeKey( 'cat-last-actions', 100 ),
720 * // Time-to-live (in seconds)
721 * 10,
722 * // Function that derives the new key value
723 * function ( $oldValue, &$ttl, array &$setOpts ) {
724 * $dbr = wfGetDB( DB_SLAVE );
725 * // Account for any snapshot/slave lag
726 * $setOpts += Database::getCacheSetOptions( $dbr );
727 *
728 * // Start off with the last cached list
729 * $list = $oldValue ?: [];
730 * // Fetch the last 100 relevant rows in descending order;
731 * // only fetch rows newer than $list[0] to reduce scanning
732 * $rows = iterator_to_array( $dbr->select( ... ) );
733 * // Merge them and get the new "last 100" rows
734 * return array_slice( array_merge( $new, $list ), 0, 100 );
735 * },
736 * // Try to only let one datacenter thread manage cache updates at a time
737 * [ 'lockTSE' => 30 ]
738 * );
739 * @endcode
740 *
741 * @see WANObjectCache::get()
742 * @see WANObjectCache::set()
743 *
744 * @param string $key Cache key
745 * @param integer $ttl Seconds to live for key updates. Special values are:
746 * - WANObjectCache::TTL_INDEFINITE: Cache forever
747 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
748 * @param callable $callback Value generation function
749 * @param array $opts Options map:
750 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
751 * touchCheckKey() or resetCheckKey() is called on any of these keys.
752 * - lowTTL: Consider pre-emptive updates when the current TTL (sec) of the key is less than
753 * this. It becomes more likely over time, becoming a certainty once the key is expired.
754 * Default: WANObjectCache::LOW_TTL seconds.
755 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
756 * ago, then try to have a single thread handle cache regeneration at any given time.
757 * Other threads will try to use stale values if possible. If, on miss, the time since
758 * expiration is low, the assumption is that the key is hot and that a stampede is worth
759 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
760 * higher this is set, the higher the worst-case staleness can be.
761 * Use WANObjectCache::TSE_NONE to disable this logic.
762 * Default: WANObjectCache::TSE_NONE.
763 * - pcTTL : process cache the value in this PHP instance with this TTL. This avoids
764 * network I/O when a key is read several times. This will not cache if the callback
765 * returns false however. Note that any purges will not be seen while process cached;
766 * since the callback should use slave DBs and they may be lagged or have snapshot
767 * isolation anyway, this should not typically matter.
768 * Default: WANObjectCache::TTL_UNCACHEABLE.
769 * @return mixed Value to use for the key
770 */
771 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
772 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
773
774 // Try the process cache if enabled
775 $value = ( $pcTTL >= 0 ) ? $this->procCache->get( $key ) : false;
776
777 if ( $value === false ) {
778 // Fetch the value over the network
779 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
780 // Update the process cache if enabled
781 if ( $pcTTL >= 0 && $value !== false ) {
782 $this->procCache->set( $key, $value, $pcTTL );
783 }
784 }
785
786 return $value;
787 }
788
789 /**
790 * Do the actual I/O for getWithSetCallback() when needed
791 *
792 * @see WANObjectCache::getWithSetCallback()
793 *
794 * @param string $key
795 * @param integer $ttl
796 * @param callback $callback
797 * @param array $opts
798 * @return mixed
799 */
800 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts ) {
801 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
802 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
803 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
804
805 // Get the current key value
806 $curTTL = null;
807 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
808 $value = $cValue; // return value
809
810 // Determine if a regeneration is desired
811 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
812 return $value;
813 }
814
815 // A deleted key with a negative TTL left must be tombstoned
816 $isTombstone = ( $curTTL !== null && $value === false );
817 // Assume a key is hot if requested soon after invalidation
818 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
819 // Decide whether a single thread should handle regenerations.
820 // This avoids stampedes when $checkKeys are bumped and when preemptive
821 // renegerations take too long. It also reduces regenerations while $key
822 // is tombstoned. This balances cache freshness with avoiding DB load.
823 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) );
824
825 $lockAcquired = false;
826 if ( $useMutex ) {
827 // Acquire a datacenter-local non-blocking lock
828 if ( $this->cache->lock( $key, 0, self::LOCK_TTL ) ) {
829 // Lock acquired; this thread should update the key
830 $lockAcquired = true;
831 } elseif ( $value !== false ) {
832 // If it cannot be acquired; then the stale value can be used
833 return $value;
834 } else {
835 // Use the stash value for tombstoned keys to reduce regeneration load.
836 // For hot keys, either another thread has the lock or the lock failed;
837 // use the stash value from the last thread that regenerated it.
838 $value = $this->cache->get( self::STASH_KEY_PREFIX . $key );
839 if ( $value !== false ) {
840 return $value;
841 }
842 }
843 }
844
845 if ( !is_callable( $callback ) ) {
846 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
847 }
848
849 // Generate the new value from the callback...
850 $setOpts = [];
851 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts ] );
852 // When delete() is called, writes are write-holed by the tombstone,
853 // so use a special stash key to pass the new value around threads.
854 if ( $useMutex && $value !== false && $ttl >= 0 ) {
855 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
856 $this->cache->set( self::STASH_KEY_PREFIX . $key, $value, $tempTTL );
857 }
858
859 if ( $lockAcquired ) {
860 $this->cache->unlock( $key );
861 }
862
863 if ( $value !== false && $ttl >= 0 ) {
864 // Update the cache; this will fail if the key is tombstoned
865 $setOpts['lockTSE'] = $lockTSE;
866 $this->set( $key, $value, $ttl, $setOpts );
867 }
868
869 return $value;
870 }
871
872 /**
873 * @see BagOStuff::makeKey()
874 * @param string ... Key component
875 * @return string
876 * @since 1.27
877 */
878 public function makeKey() {
879 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
880 }
881
882 /**
883 * @see BagOStuff::makeGlobalKey()
884 * @param string ... Key component
885 * @return string
886 * @since 1.27
887 */
888 public function makeGlobalKey() {
889 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
890 }
891
892 /**
893 * Get the "last error" registered; clearLastError() should be called manually
894 * @return int ERR_* constant for the "last error" registry
895 */
896 final public function getLastError() {
897 if ( $this->lastRelayError ) {
898 // If the cache and the relayer failed, focus on the later.
899 // An update not making it to the relayer means it won't show up
900 // in other DCs (nor will consistent re-hashing see up-to-date values).
901 // On the other hand, if just the cache update failed, then it should
902 // eventually be applied by the relayer.
903 return $this->lastRelayError;
904 }
905
906 $code = $this->cache->getLastError();
907 switch ( $code ) {
908 case BagOStuff::ERR_NONE:
909 return self::ERR_NONE;
910 case BagOStuff::ERR_NO_RESPONSE:
911 return self::ERR_NO_RESPONSE;
912 case BagOStuff::ERR_UNREACHABLE:
913 return self::ERR_UNREACHABLE;
914 default:
915 return self::ERR_UNEXPECTED;
916 }
917 }
918
919 /**
920 * Clear the "last error" registry
921 */
922 final public function clearLastError() {
923 $this->cache->clearLastError();
924 $this->lastRelayError = self::ERR_NONE;
925 }
926
927 /**
928 * Clear the in-process caches; useful for testing
929 *
930 * @since 1.27
931 */
932 public function clearProcessCache() {
933 $this->procCache->clear();
934 }
935
936 /**
937 * Do the actual async bus purge of a key
938 *
939 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
940 *
941 * @param string $key Cache key
942 * @param integer $ttl How long to keep the tombstone [seconds]
943 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
944 * @return bool Success
945 */
946 protected function relayPurge( $key, $ttl, $holdoff ) {
947 $event = $this->cache->modifySimpleRelayEvent( [
948 'cmd' => 'set',
949 'key' => $key,
950 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
951 'ttl' => max( $ttl, 1 ),
952 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
953 ] );
954
955 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
956 if ( !$ok ) {
957 $this->lastRelayError = self::ERR_RELAY;
958 }
959
960 return $ok;
961 }
962
963 /**
964 * Do the actual async bus delete of a key
965 *
966 * @param string $key Cache key
967 * @return bool Success
968 */
969 protected function relayDelete( $key ) {
970 $event = $this->cache->modifySimpleRelayEvent( [
971 'cmd' => 'delete',
972 'key' => $key,
973 ] );
974
975 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
976 if ( !$ok ) {
977 $this->lastRelayError = self::ERR_RELAY;
978 }
979
980 return $ok;
981 }
982
983 /**
984 * Check if a key should be regenerated (using random probability)
985 *
986 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
987 * of returning true increases steadily from 0% to 100% as the $curTTL
988 * moves from $lowTTL to 0 seconds. This handles widely varying
989 * levels of cache access traffic.
990 *
991 * @param float $curTTL Approximate TTL left on the key if present
992 * @param float $lowTTL Consider a refresh when $curTTL is less than this
993 * @return bool
994 */
995 protected function worthRefresh( $curTTL, $lowTTL ) {
996 if ( $curTTL >= $lowTTL ) {
997 return false;
998 } elseif ( $curTTL <= 0 ) {
999 return true;
1000 }
1001
1002 $chance = ( 1 - $curTTL / $lowTTL );
1003
1004 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1005 }
1006
1007 /**
1008 * Do not use this method outside WANObjectCache
1009 *
1010 * @param mixed $value
1011 * @param integer $ttl [0=forever]
1012 * @return array
1013 */
1014 protected function wrap( $value, $ttl ) {
1015 return [
1016 self::FLD_VERSION => self::VERSION,
1017 self::FLD_VALUE => $value,
1018 self::FLD_TTL => $ttl,
1019 self::FLD_TIME => microtime( true )
1020 ];
1021 }
1022
1023 /**
1024 * Do not use this method outside WANObjectCache
1025 *
1026 * @param array|string|bool $wrapped
1027 * @param float $now Unix Current timestamp (preferrable pre-query)
1028 * @return array (mixed; false if absent/invalid, current time left)
1029 */
1030 protected function unwrap( $wrapped, $now ) {
1031 // Check if the value is a tombstone
1032 $purge = self::parsePurgeValue( $wrapped );
1033 if ( $purge !== false ) {
1034 // Purged values should always have a negative current $ttl
1035 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1036 return [ false, $curTTL ];
1037 }
1038
1039 if ( !is_array( $wrapped ) // not found
1040 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1041 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1042 ) {
1043 return [ false, null ];
1044 }
1045
1046 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1047 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1048 // Treat as expired, with the cache time as the expiration
1049 $age = $now - $wrapped[self::FLD_TIME];
1050 $curTTL = min( -$age, self::TINY_NEGATIVE );
1051 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1052 // Get the approximate time left on the key
1053 $age = $now - $wrapped[self::FLD_TIME];
1054 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1055 } else {
1056 // Key had no TTL, so the time left is unbounded
1057 $curTTL = INF;
1058 }
1059
1060 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1061 }
1062
1063 /**
1064 * @param array $keys
1065 * @param string $prefix
1066 * @return string[]
1067 */
1068 protected static function prefixCacheKeys( array $keys, $prefix ) {
1069 $res = [];
1070 foreach ( $keys as $key ) {
1071 $res[] = $prefix . $key;
1072 }
1073
1074 return $res;
1075 }
1076
1077 /**
1078 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1079 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1080 * or false if value isn't a valid purge value
1081 */
1082 protected static function parsePurgeValue( $value ) {
1083 if ( !is_string( $value ) ) {
1084 return false;
1085 }
1086 $segments = explode( ':', $value, 3 );
1087 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1088 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1089 ) {
1090 return false;
1091 }
1092 if ( !isset( $segments[2] ) ) {
1093 // Back-compat with old purge values without holdoff
1094 $segments[2] = self::HOLDOFF_TTL;
1095 }
1096 return [
1097 self::FLD_TIME => (float)$segments[1],
1098 self::FLD_HOLDOFF => (int)$segments[2],
1099 ];
1100 }
1101
1102 /**
1103 * @param float $timestamp
1104 * @param int $holdoff In seconds
1105 * @return string Wrapped purge value
1106 */
1107 protected function makePurgeValue( $timestamp, $holdoff ) {
1108 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1109 }
1110 }