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