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