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