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