Merge "Allow for dynamic TTLs in getWithSetCallback()"
[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 cache, except the delete()
27 * and touchCheckKey(), which broadcast to all clusters.
28 * This class is intended for caching data from primary stores.
29 * If the get() method does not return a value, then the caller
30 * should query the new value and backfill the cache using set().
31 * When the source data changes, the delete() method should be called.
32 * Since delete() is expensive, it should be avoided. One can do so if:
33 * - a) The object cached is immutable; or
34 * - b) Validity is checked against the source after get(); or
35 * - c) Using a modest TTL is reasonably correct and performant
36 * Consider using getWithSetCallback() instead of the get()/set() cycle.
37 *
38 * Instances of this class must be configured to point to a valid
39 * PubSub endpoint, and there must be listeners on the cache servers
40 * that subscribe to the endpoint and update the caches.
41 *
42 * Broadcasted operations like delete() and touchCheckKey() are done
43 * synchronously in the local cluster, but are relayed asynchronously.
44 * This means that callers in other datacenters will see older values
45 * for a however many milliseconds the datacenters are apart. As with
46 * any cache, this should not be relied on for cases where reads are
47 * used to determine writes to source (e.g. non-cache) data stores.
48 *
49 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
50 * to avoid collisions with keys that are not wrapped as metadata arrays. The
51 * prefixes are as follows:
52 * - a) "WANCache:v" : used for regular value keys
53 * - b) "WANCache:s" : used for temporarily storing values of tombstoned keys
54 * - c) "WANCache:t" : used for storing timestamp "check" keys
55 *
56 * @ingroup Cache
57 * @since 1.26
58 */
59 class WANObjectCache {
60 /** @var BagOStuff The local cluster cache */
61 protected $cache;
62 /** @var string Cache pool name */
63 protected $pool;
64 /** @var EventRelayer */
65 protected $relayer;
66
67 /** @var int */
68 protected $lastRelayError = self::ERR_NONE;
69
70 /** Seconds to tombstone keys on delete() */
71 const HOLDOFF_TTL = 10;
72 /** Seconds to keep dependency purge keys around */
73 const CHECK_KEY_TTL = 31536000; // 1 year
74 /** Seconds to keep lock keys around */
75 const LOCK_TTL = 5;
76
77 /** Idiom for set()/getWithSetCallback() TTL */
78 const TTL_NONE = 0;
79
80 /** Cache format version number */
81 const VERSION = 1;
82
83 /** Fields of value holder arrays */
84 const FLD_VERSION = 0;
85 const FLD_VALUE = 1;
86 const FLD_TTL = 2;
87 const FLD_TIME = 3;
88
89 /** Possible values for getLastError() */
90 const ERR_NONE = 0; // no error
91 const ERR_NO_RESPONSE = 1; // no response
92 const ERR_UNREACHABLE = 2; // can't connect
93 const ERR_UNEXPECTED = 3; // response gave some error
94 const ERR_RELAY = 4; // relay broadcast failed
95
96 const VALUE_KEY_PREFIX = 'WANCache:v:';
97 const STASH_KEY_PREFIX = 'WANCache:s:';
98 const TIME_KEY_PREFIX = 'WANCache:t:';
99
100 const PURGE_VAL_PREFIX = 'PURGED:';
101
102 /**
103 * @param array $params
104 * - cache : BagOStuff object
105 * - pool : pool name
106 * - relayer : EventRelayer object
107 */
108 public function __construct( array $params ) {
109 $this->cache = $params['cache'];
110 $this->pool = $params['pool'];
111 $this->relayer = $params['relayer'];
112 }
113
114 /**
115 * Fetch the value of a key from cache
116 *
117 * If passed in, $curTTL is set to the remaining TTL (current time left):
118 * - a) INF; if the key exists and has no TTL
119 * - b) float (>=0); if the key exists and has a TTL
120 * - c) float (<0); if the key is tombstoned or expired by $checkKeys
121 * - d) null; if the key does not exist and is not tombstoned
122 *
123 * If a key is tombstoned, $curTTL will reflect the time since delete().
124 *
125 * The timestamp of $key will be checked against the last-purge timestamp
126 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
127 * initialized to the current timestamp. If any of $checkKeys have a timestamp
128 * greater than that of $key, then $curTTL will reflect how long ago $key
129 * became invalid. Callers can use $curTTL to know when the value is stale.
130 * The $checkKeys parameter allow mass invalidations by updating a single key:
131 * - a) Each "check" key represents "last purged" of some source data
132 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
133 * - c) When the source data that "check" keys represent changes,
134 * the touchCheckKey() method is called on them
135 *
136 * For keys that are hot/expensive, consider using getWithSetCallback() instead.
137 *
138 * @param string $key Cache key
139 * @param mixed $curTTL Approximate TTL left on the key if present [returned]
140 * @param array $checkKeys List of "check" keys
141 * @return mixed Value of cache key or false on failure
142 */
143 final public function get( $key, &$curTTL = null, array $checkKeys = array() ) {
144 $curTTLs = array();
145 $values = $this->getMulti( array( $key ), $curTTLs, $checkKeys );
146 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
147
148 return isset( $values[$key] ) ? $values[$key] : false;
149 }
150
151 /**
152 * Fetch the value of several keys from cache
153 *
154 * @see WANObjectCache::get()
155 *
156 * @param array $keys List of cache keys
157 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
158 * @param array $checkKeys List of "check" keys
159 * @return array Map of (key => value) for keys that exist
160 */
161 final public function getMulti(
162 array $keys, &$curTTLs = array(), array $checkKeys = array()
163 ) {
164 $result = array();
165 $curTTLs = array();
166
167 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
168 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
169 $checkKeys = self::prefixCacheKeys( $checkKeys, self::TIME_KEY_PREFIX );
170
171 // Fetch all of the raw values
172 $wrappedValues = $this->cache->getMulti( array_merge( $valueKeys, $checkKeys ) );
173 $now = microtime( true );
174
175 // Get/initialize the timestamp of all the "check" keys
176 $checkKeyTimes = array();
177 foreach ( $checkKeys as $checkKey ) {
178 $timestamp = isset( $wrappedValues[$checkKey] )
179 ? self::parsePurgeValue( $wrappedValues[$checkKey] )
180 : false;
181 if ( !is_float( $timestamp ) ) {
182 // Key is not set or invalid; regenerate
183 $this->cache->add( $checkKey,
184 self::PURGE_VAL_PREFIX . $now, self::CHECK_KEY_TTL );
185 $timestamp = $now;
186 }
187
188 $checkKeyTimes[] = $timestamp;
189 }
190
191 // Get the main cache value for each key and validate them
192 foreach ( $valueKeys as $vKey ) {
193 if ( !isset( $wrappedValues[$vKey] ) ) {
194 continue; // not found
195 }
196
197 $key = substr( $vKey, $vPrefixLen ); // unprefix
198
199 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
200 if ( $value !== false ) {
201 $result[$key] = $value;
202 foreach ( $checkKeyTimes as $checkKeyTime ) {
203 // Force dependant keys to be invalid for a while after purging
204 // to reduce race conditions involving stale data getting cached
205 $safeTimestamp = $checkKeyTime + self::HOLDOFF_TTL;
206 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
207 $curTTL = min( $curTTL, $checkKeyTime - $now );
208 }
209 }
210 }
211
212 $curTTLs[$key] = $curTTL;
213 }
214
215 return $result;
216 }
217
218 /**
219 * Set the value of a key from cache
220 *
221 * Simply calling this method when source data changes is not valid because
222 * the changes do not replicate to the other WAN sites. In that case, delete()
223 * should be used instead. This method is intended for use on cache misses.
224 *
225 * @param string $key Cache key
226 * @param mixed $value
227 * @param integer $ttl Seconds to live [0=forever]
228 * @return bool Success
229 */
230 final public function set( $key, $value, $ttl = 0 ) {
231 $key = self::VALUE_KEY_PREFIX . $key;
232 $wrapped = $this->wrap( $value, $ttl );
233
234 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
235 return ( is_string( $cWrapped ) )
236 ? false // key is tombstoned; do nothing
237 : $wrapped;
238 };
239
240 return $this->cache->merge( $key, $func, $ttl, 1 );
241 }
242
243 /**
244 * Purge a key from all clusters
245 *
246 * This instantiates a hold-off period where the key cannot be
247 * written to avoid race conditions where dependent keys get updated
248 * with a stale value (e.g. from a DB slave).
249 *
250 * This should only be called when the underlying data (being cached)
251 * changes in a significant way. If called twice on the same key, then
252 * the last TTL takes precedence.
253 *
254 * @param string $key Cache key
255 * @param integer $ttl How long to block writes to the key [seconds]
256 * @return bool True if the item was purged or not found, false on failure
257 */
258 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
259 $key = self::VALUE_KEY_PREFIX . $key;
260 // Update the local cluster immediately
261 $ok = $this->cache->set( $key, self::PURGE_VAL_PREFIX . microtime( true ), $ttl );
262 // Publish the purge to all clusters
263 return $this->relayPurge( $key, $ttl ) && $ok;
264 }
265
266 /**
267 * Fetch the value of a timestamp "check" key
268 *
269 * Note that "check" keys won't collide with other regular keys
270 *
271 * @param string $key
272 * @return float|bool TS_UNIX timestamp of the key; false if not present
273 */
274 final public function getCheckKeyTime( $key ) {
275 return self::parsePurgeValue( $this->cache->get( self::TIME_KEY_PREFIX . $key ) );
276 }
277
278 /**
279 * Purge a "check" key from all clusters, invalidating keys that use it
280 *
281 * This should only be called when the underlying data (being cached)
282 * changes in a significant way, and it is impractical to call delete()
283 * on all keys that should be changed. When get() is called on those
284 * keys, the relevant "check" keys must be supplied for this to work.
285 *
286 * The "check" key essentially represents a last-modified field.
287 * It is set in the future a few seconds when this is called, to
288 * avoid race conditions where dependent keys get updated with a
289 * stale value (e.g. from a DB slave).
290 *
291 * Note that "check" keys won't collide with other regular keys
292 *
293 * @see WANObjectCache::get()
294 *
295 * @param string $key Cache key
296 * @return bool True if the item was purged or not found, false on failure
297 */
298 final public function touchCheckKey( $key ) {
299 $key = self::TIME_KEY_PREFIX . $key;
300 // Update the local cluster immediately
301 $ok = $this->cache->set( $key,
302 self::PURGE_VAL_PREFIX . microtime( true ), self::CHECK_KEY_TTL );
303 // Publish the purge to all clusters
304 return $this->relayPurge( $key, self::CHECK_KEY_TTL ) && $ok;
305 }
306
307 /**
308 * Method to fetch/regenerate cache keys
309 *
310 * On cache miss, the key will be set to the callback result,
311 * unless the callback returns false. The arguments supplied are:
312 * (current value or false, &$ttl)
313 * The callback function returns the new value given the current
314 * value (false if not present). Preemptive re-caching and $checkKeys
315 * can result in a non-false current value. The TTL of the new value
316 * can be set dynamically by altering $ttl in the callback (by reference).
317 *
318 * Usually, callbacks ignore the current value, but it can be used
319 * to maintain "most recent X" values that come from time or sequence
320 * based source data, provided that the "as of" id/time is tracked.
321 *
322 * Usage of $checkKeys is similar to get()/getMulti(). However,
323 * rather than the caller having to inspect a "current time left"
324 * variable (e.g. $curTTL, $curTTLs), a cache regeneration will be
325 * triggered using the callback.
326 *
327 * The simplest way to avoid stampedes for hot keys is to use
328 * the 'lockTSE' option in $opts. If cache purges are needed, also:
329 * a) Pass $key into $checkKeys
330 * b) Use touchCheckKey( $key ) instead of delete( $key )
331 * Following this pattern lets the old cache be used until a
332 * single thread updates it as needed. Also consider tweaking
333 * the 'lowTTL' parameter.
334 *
335 * Example usage:
336 * @code
337 * $key = wfMemcKey( 'cat-recent-actions', $catId );
338 * // Function that derives the new key value given the old value
339 * $callback = function( $cValue, &$ttl ) { ... };
340 * // Get the key value from cache or from source on cache miss;
341 * // try to only let one cluster thread manage doing cache updates
342 * $opts = array( 'lockTSE' => 5, 'lowTTL' => 10 );
343 * $value = $cache->getWithSetCallback( $key, $callback, 60, array(), $opts );
344 * @endcode
345 *
346 * Example usage:
347 * @code
348 * $key = wfMemcKey( 'cat-state', $catId );
349 * // The "check" keys that represent things the value depends on;
350 * // Calling touchCheckKey() on them invalidates "cat-state"
351 * $checkKeys = array(
352 * wfMemcKey( 'water-bowls', $houseId ),
353 * wfMemcKey( 'food-bowls', $houseId ),
354 * wfMemcKey( 'people-present', $houseId )
355 * );
356 * // Function that derives the new key value
357 * $callback = function() { ... };
358 * // Get the key value from cache or from source on cache miss;
359 * // try to only let one cluster thread manage doing cache updates
360 * $opts = array( 'lockTSE' => 5, 'lowTTL' => 10 );
361 * $value = $cache->getWithSetCallback( $key, $callback, 60, $checkKeys, $opts );
362 * @endcode
363 *
364 * @see WANObjectCache::get()
365 *
366 * @param string $key Cache key
367 * @param callable $callback Value generation function
368 * @param integer $ttl Seconds to live when the key is updated [0=forever]
369 * @param array $checkKeys List of "check" keys
370 * @param array $opts Options map:
371 * - lowTTL : consider pre-emptive updates when the current TTL (sec)
372 * of the key is less than this. It becomes more likely
373 * over time, becoming a certainty once the key is expired.
374 * - lockTSE : if the key is tombstoned or expired (by $checkKeys) less
375 * than this many seconds ago, then try to have a single
376 * thread handle cache regeneration at any given time.
377 * Other threads will try to use stale values if possible.
378 * If, on miss, the time since expiration is low, the assumption
379 * is that the key is hot and that a stampede is worth avoiding.
380 * - tempTTL : when 'lockTSE' is set, this determines the TTL of the temp
381 * key used to cache values while a key is tombstoned.
382 * This avoids excessive regeneration of hot keys on delete() but
383 * may result in stale values.
384 * @return mixed Value to use for the key
385 */
386 final public function getWithSetCallback(
387 $key, $callback, $ttl, array $checkKeys = array(), array $opts = array()
388 ) {
389 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( 10, $ttl );
390 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : -1;
391 $tempTTL = isset( $opts['tempTTL'] ) ? $opts['tempTTL'] : 5;
392
393 // Get the current key value
394 $curTTL = null;
395 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
396 $value = $cValue; // return value
397
398 // Determine if a regeneration is desired
399 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
400 return $value;
401 }
402
403 if ( !is_callable( $callback ) ) {
404 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
405 }
406
407 // Assume a key is hot if requested soon after invalidation
408 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
409 $isTombstone = ( $curTTL !== null && $value === false );
410
411 $locked = false;
412 if ( $isHot || $isTombstone ) {
413 // Acquire a cluster-local non-blocking lock
414 if ( $this->cache->lock( $key, 0, self::LOCK_TTL ) ) {
415 // Lock acquired; this thread should update the key
416 $locked = true;
417 } elseif ( $value !== false ) {
418 // If it cannot be acquired; then the stale value can be used
419 return $value;
420 } else {
421 // Either another thread has the lock or the lock failed.
422 // Use the stash value, which is likely from the prior thread.
423 $value = $this->cache->get( self::STASH_KEY_PREFIX . $key );
424 // Regenerate on timeout or if the other thread failed
425 if ( $value !== false ) {
426 return $value;
427 }
428 }
429 }
430
431 // Generate the new value from the callback...
432 $value = call_user_func_array( $callback, array( $cValue, &$ttl ) );
433 // When delete() is called, writes are write-holed by the tombstone,
434 // so use a special stash key to pass the new value around threads.
435 if ( $value !== false && ( $isHot || $isTombstone ) ) {
436 $this->cache->set( self::STASH_KEY_PREFIX . $key, $value, $tempTTL );
437 }
438
439 if ( $locked ) {
440 $this->cache->unlock( $key );
441 }
442
443 if ( $value !== false ) {
444 // Update the cache; this will fail if the key is tombstoned
445 $this->set( $key, $value, $ttl );
446 }
447
448 return $value;
449 }
450
451 /**
452 * Get the "last error" registered; clearLastError() should be called manually
453 * @return int ERR_* constant for the "last error" registry
454 */
455 final public function getLastError() {
456 if ( $this->lastRelayError ) {
457 // If the cache and the relayer failed, focus on the later.
458 // An update not making it to the relayer means it won't show up
459 // in other DCs (nor will consistent re-hashing see up-to-date values).
460 // On the other hand, if just the cache update failed, then it should
461 // eventually be applied by the relayer.
462 return $this->lastRelayError;
463 }
464
465 $code = $this->cache->getLastError();
466 switch ( $code ) {
467 case BagOStuff::ERR_NONE:
468 return self::ERR_NONE;
469 case BagOStuff::ERR_NO_RESPONSE:
470 return self::ERR_NO_RESPONSE;
471 case BagOStuff::ERR_UNREACHABLE:
472 return self::ERR_UNREACHABLE;
473 default:
474 return self::ERR_UNEXPECTED;
475 }
476 }
477
478 /**
479 * Clear the "last error" registry
480 */
481 final public function clearLastError() {
482 $this->cache->clearLastError();
483 $this->lastRelayError = self::ERR_NONE;
484 }
485
486 /**
487 * Do the actual async bus purge of a key
488 *
489 * This must set the key to "PURGED:<UNIX timestamp>"
490 *
491 * @param string $key Cache key
492 * @param integer $ttl How long to keep the tombstone [seconds]
493 * @return bool Success
494 */
495 protected function relayPurge( $key, $ttl ) {
496 $event = $this->cache->modifySimpleRelayEvent( array(
497 'cmd' => 'set',
498 'key' => $key,
499 'val' => 'PURGED:$UNIXTIME$',
500 'ttl' => max( $ttl, 1 ),
501 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
502 ) );
503
504 $ok = $this->relayer->notify( "{$this->pool}:purge", $event );
505 if ( !$ok ) {
506 $this->lastRelayError = self::ERR_RELAY;
507 }
508
509 return $ok;
510 }
511
512 /**
513 * Check if a key should be regenerated (using random probability)
514 *
515 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
516 * of returning true increases steadily from 0% to 100% as the $curTTL
517 * moves from $lowTTL to 0 seconds. This handles widely varying
518 * levels of cache access traffic.
519 *
520 * @param float|INF $curTTL Approximate TTL left on the key if present
521 * @param float $lowTTL Consider a refresh when $curTTL is less than this
522 * @return bool
523 */
524 protected function worthRefresh( $curTTL, $lowTTL ) {
525 if ( $curTTL >= $lowTTL ) {
526 return false;
527 } elseif ( $curTTL <= 0 ) {
528 return true;
529 }
530
531 $chance = ( 1 - $curTTL / $lowTTL );
532
533 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
534 }
535
536 /**
537 * Do not use this method outside WANObjectCache
538 *
539 * @param mixed $value
540 * @param integer $ttl [0=forever]
541 * @return string
542 */
543 protected function wrap( $value, $ttl ) {
544 return array(
545 self::FLD_VERSION => self::VERSION,
546 self::FLD_VALUE => $value,
547 self::FLD_TTL => $ttl,
548 self::FLD_TIME => microtime( true )
549 );
550 }
551
552 /**
553 * Do not use this method outside WANObjectCache
554 *
555 * @param array|string|bool $wrapped
556 * @param float $now Unix Current timestamp (preferrable pre-query)
557 * @return array (mixed; false if absent/invalid, current time left)
558 */
559 protected function unwrap( $wrapped, $now ) {
560 // Check if the value is a tombstone
561 $purgeTimestamp = self::parsePurgeValue( $wrapped );
562 if ( is_float( $purgeTimestamp ) ) {
563 // Purged values should always have a negative current $ttl
564 $curTTL = min( -0.000001, $purgeTimestamp - $now );
565 return array( false, $curTTL );
566 }
567
568 if ( !is_array( $wrapped ) // not found
569 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
570 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
571 ) {
572 return array( false, null );
573 }
574
575 if ( $wrapped[self::FLD_TTL] > 0 ) {
576 // Get the approximate time left on the key
577 $age = $now - $wrapped[self::FLD_TIME];
578 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
579 } else {
580 // Key had no TTL, so the time left is unbounded
581 $curTTL = INF;
582 }
583
584 return array( $wrapped[self::FLD_VALUE], $curTTL );
585 }
586
587 /**
588 * @param array $keys
589 * @param string $prefix
590 * @return string[]
591 */
592 protected static function prefixCacheKeys( array $keys, $prefix ) {
593 $res = array();
594 foreach ( $keys as $key ) {
595 $res[] = $prefix . $key;
596 }
597
598 return $res;
599 }
600
601 /**
602 * @param string $value String like "PURGED:<timestamp>"
603 * @return float|bool UNIX timestamp or false on failure
604 */
605 protected static function parsePurgeValue( $value ) {
606 $m = array();
607 if ( is_string( $value ) &&
608 preg_match( '/^' . self::PURGE_VAL_PREFIX . '([^:]+)$/', $value, $m )
609 ) {
610 return (float)$m[1];
611 } else {
612 return false;
613 }
614 }
615 }