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