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