Merge "Use a constructive button on Special:MovePage"
[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 * If called twice on the same key, then the last hold-off TTL takes
290 * precedence. For idempotence, the $ttl should not vary for different
291 * delete() calls on the same key. Also note that lowering $ttl reduces
292 * the effective range of the 'lockTSE' parameter to getWithSetCallback().
293 *
294 * @param string $key Cache key
295 * @param integer $ttl How long to block writes to the key [seconds]
296 * @return bool True if the item was purged or not found, false on failure
297 */
298 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
299 $key = self::VALUE_KEY_PREFIX . $key;
300 // Avoid indefinite key salting for sanity
301 $ttl = max( $ttl, 1 );
302 // Update the local cluster immediately
303 $ok = $this->cache->set( $key, self::PURGE_VAL_PREFIX . microtime( true ), $ttl );
304 // Publish the purge to all clusters
305 return $this->relayPurge( $key, $ttl ) && $ok;
306 }
307
308 /**
309 * Fetch the value of a timestamp "check" key
310 *
311 * The key will be *initialized* to the current time if not set,
312 * so only call this method if this behavior is actually desired
313 *
314 * The timestamp can be used to check whether a cached value is valid.
315 * Callers should not assume that this returns the same timestamp in
316 * all datacenters due to relay delays.
317 *
318 * The level of staleness can roughly be estimated from this key, but
319 * if the key was evicted from cache, such calculations may show the
320 * time since expiry as ~0 seconds.
321 *
322 * Note that "check" keys won't collide with other regular keys
323 *
324 * @param string $key
325 * @return float UNIX timestamp of the key
326 */
327 final public function getCheckKeyTime( $key ) {
328 $key = self::TIME_KEY_PREFIX . $key;
329
330 $time = self::parsePurgeValue( $this->cache->get( $key ) );
331 if ( $time === false ) {
332 // Casting assures identical floats for the next getCheckKeyTime() calls
333 $time = (string)microtime( true );
334 $this->cache->add( $key, self::PURGE_VAL_PREFIX . $time, self::CHECK_KEY_TTL );
335 $time = (float)$time;
336 }
337
338 return $time;
339 }
340
341 /**
342 * Purge a "check" key from all clusters, invalidating keys that use it
343 *
344 * This should only be called when the underlying data (being cached)
345 * changes in a significant way, and it is impractical to call delete()
346 * on all keys that should be changed. When get() is called on those
347 * keys, the relevant "check" keys must be supplied for this to work.
348 *
349 * The "check" key essentially represents a last-modified field.
350 * It is set in the future a few seconds when this is called, to
351 * avoid race conditions where dependent keys get updated with a
352 * stale value (e.g. from a DB slave).
353 *
354 * This is typically useful for keys with static names or some cases
355 * dynamically generated names where a low number of combinations exist.
356 * When a few important keys get a large number of hits, a high cache
357 * time is usually desired as well as lockTSE logic. The resetCheckKey()
358 * method is less appropriate in such cases since the "time since expiry"
359 * cannot be inferred.
360 *
361 * Note that "check" keys won't collide with other regular keys
362 *
363 * @see WANObjectCache::get()
364 *
365 * @param string $key Cache key
366 * @return bool True if the item was purged or not found, false on failure
367 */
368 final public function touchCheckKey( $key ) {
369 $key = self::TIME_KEY_PREFIX . $key;
370 // Update the local cluster immediately
371 $ok = $this->cache->set( $key,
372 self::PURGE_VAL_PREFIX . microtime( true ), self::CHECK_KEY_TTL );
373 // Publish the purge to all clusters
374 return $this->relayPurge( $key, self::CHECK_KEY_TTL ) && $ok;
375 }
376
377 /**
378 * Delete a "check" key from all clusters, invalidating keys that use it
379 *
380 * This is similar to touchCheckKey() in that keys using it via
381 * getWithSetCallback() will be invalidated. The differences are:
382 * - a) The timestamp will be deleted from all caches and lazily
383 * re-initialized when accessed (rather than set everywhere)
384 * - b) Thus, dependent keys will be known to be invalid, but not
385 * for how long (they are treated as "just" purged), which
386 * effects any lockTSE logic in getWithSetCallback()
387 * The advantage is that this does not place high TTL keys on every cache
388 * server, making it better for code that will cache many different keys
389 * and either does not use lockTSE or uses a low enough TTL anyway.
390 *
391 * This is typically useful for keys with dynamically generated names
392 * where a high number of combinations exist.
393 *
394 * Note that "check" keys won't collide with other regular keys
395 *
396 * @see WANObjectCache::touchCheckKey()
397 * @see WANObjectCache::get()
398 *
399 * @param string $key Cache key
400 * @return bool True if the item was purged or not found, false on failure
401 */
402 final public function resetCheckKey( $key ) {
403 $key = self::TIME_KEY_PREFIX . $key;
404 // Update the local cluster immediately
405 $ok = $this->cache->delete( $key );
406 // Publish the purge to all clusters
407 return $this->relayDelete( $key ) && $ok;
408 }
409
410 /**
411 * Method to fetch/regenerate cache keys
412 *
413 * On cache miss, the key will be set to the callback result,
414 * unless the callback returns false. The arguments supplied are:
415 * (current value or false, &$ttl)
416 * The callback function returns the new value given the current
417 * value (false if not present). Preemptive re-caching and $checkKeys
418 * can result in a non-false current value. The TTL of the new value
419 * can be set dynamically by altering $ttl in the callback (by reference).
420 *
421 * Usually, callbacks ignore the current value, but it can be used
422 * to maintain "most recent X" values that come from time or sequence
423 * based source data, provided that the "as of" id/time is tracked.
424 *
425 * Usage of $checkKeys is similar to get() and getMulti(). However,
426 * rather than the caller having to inspect a "current time left"
427 * variable (e.g. $curTTL, $curTTLs), a cache regeneration will be
428 * triggered using the callback.
429 *
430 * The simplest way to avoid stampedes for hot keys is to use
431 * the 'lockTSE' option in $opts. If cache purges are needed, also:
432 * - a) Pass $key into $checkKeys
433 * - b) Use touchCheckKey( $key ) instead of delete( $key )
434 * Following this pattern lets the old cache be used until a
435 * single thread updates it as needed. Also consider tweaking
436 * the 'lowTTL' parameter.
437 *
438 * Example usage:
439 * @code
440 * $key = wfMemcKey( 'cat-recent-actions', $catId );
441 * // Function that derives the new key value given the old value
442 * $callback = function( $cValue, &$ttl ) { ... };
443 * // Get the key value from cache or from source on cache miss;
444 * // try to only let one cluster thread manage doing cache updates
445 * $opts = array( 'lockTSE' => 5, 'lowTTL' => 10 );
446 * $value = $cache->getWithSetCallback( $key, $callback, 60, array(), $opts );
447 * @endcode
448 *
449 * Example usage:
450 * @code
451 * $key = wfMemcKey( 'cat-state', $catId );
452 * // The "check" keys that represent things the value depends on;
453 * // Calling touchCheckKey() on them invalidates "cat-state"
454 * $checkKeys = array(
455 * wfMemcKey( 'water-bowls', $houseId ),
456 * wfMemcKey( 'food-bowls', $houseId ),
457 * wfMemcKey( 'people-present', $houseId )
458 * );
459 * // Function that derives the new key value
460 * $callback = function() { ... };
461 * // Get the key value from cache or from source on cache miss;
462 * // try to only let one cluster thread manage doing cache updates
463 * $opts = array( 'lockTSE' => 5, 'lowTTL' => 10 );
464 * $value = $cache->getWithSetCallback( $key, $callback, 60, $checkKeys, $opts );
465 * @endcode
466 *
467 * @see WANObjectCache::get()
468 *
469 * @param string $key Cache key
470 * @param callable $callback Value generation function
471 * @param integer $ttl Seconds to live for key updates. Special values are:
472 * - WANObjectCache::TTL_NONE : cache forever
473 * - WANObjectCache::TTL_UNCACHEABLE : do not cache at all
474 * @param array $checkKeys List of "check" keys
475 * @param array $opts Options map:
476 * - lowTTL : consider pre-emptive updates when the current TTL (sec)
477 * of the key is less than this. It becomes more likely
478 * over time, becoming a certainty once the key is expired.
479 * [Default: WANObjectCache::LOW_TTL seconds]
480 * - lockTSE : if the key is tombstoned or expired (by $checkKeys) less
481 * than this many seconds ago, then try to have a single
482 * thread handle cache regeneration at any given time.
483 * Other threads will try to use stale values if possible.
484 * If, on miss, the time since expiration is low, the assumption
485 * is that the key is hot and that a stampede is worth avoiding.
486 * Setting this above WANObjectCache::HOLDOFF_TTL makes no difference.
487 * The higher this is set, the higher the worst-case staleness can be.
488 * Use WANObjectCache::TSE_NONE to disable this logic.
489 * [Default: WANObjectCache::TSE_NONE]
490 * @return mixed Value to use for the key
491 */
492 final public function getWithSetCallback(
493 $key, $callback, $ttl, array $checkKeys = array(), array $opts = array()
494 ) {
495 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
496 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
497
498 // Get the current key value
499 $curTTL = null;
500 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
501 $value = $cValue; // return value
502
503 // Determine if a regeneration is desired
504 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
505 return $value;
506 }
507
508 // A deleted key with a negative TTL left must be tombstoned
509 $isTombstone = ( $curTTL !== null && $value === false );
510 // Assume a key is hot if requested soon after invalidation
511 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
512 // Decide whether a single thread should handle regenerations.
513 // This avoids stampedes when $checkKeys are bumped and when preemptive
514 // renegerations take too long. It also reduces regenerations while $key
515 // is tombstoned. This balances cache freshness with avoiding DB load.
516 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) );
517
518 $lockAcquired = false;
519 if ( $useMutex ) {
520 // Acquire a cluster-local non-blocking lock
521 if ( $this->cache->lock( $key, 0, self::LOCK_TTL ) ) {
522 // Lock acquired; this thread should update the key
523 $lockAcquired = true;
524 } elseif ( $value !== false ) {
525 // If it cannot be acquired; then the stale value can be used
526 return $value;
527 } else {
528 // Use the stash value for tombstoned keys to reduce regeneration load.
529 // For hot keys, either another thread has the lock or the lock failed;
530 // use the stash value from the last thread that regenerated it.
531 $value = $this->cache->get( self::STASH_KEY_PREFIX . $key );
532 if ( $value !== false ) {
533 return $value;
534 }
535 }
536 }
537
538 if ( !is_callable( $callback ) ) {
539 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
540 }
541
542 // Generate the new value from the callback...
543 $value = call_user_func_array( $callback, array( $cValue, &$ttl ) );
544 // When delete() is called, writes are write-holed by the tombstone,
545 // so use a special stash key to pass the new value around threads.
546 if ( $useMutex && $value !== false && $ttl >= 0 ) {
547 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
548 $this->cache->set( self::STASH_KEY_PREFIX . $key, $value, $tempTTL );
549 }
550
551 if ( $lockAcquired ) {
552 $this->cache->unlock( $key );
553 }
554
555 if ( $value !== false && $ttl >= 0 ) {
556 // Update the cache; this will fail if the key is tombstoned
557 $this->set( $key, $value, $ttl );
558 }
559
560 return $value;
561 }
562
563 /**
564 * Get the "last error" registered; clearLastError() should be called manually
565 * @return int ERR_* constant for the "last error" registry
566 */
567 final public function getLastError() {
568 if ( $this->lastRelayError ) {
569 // If the cache and the relayer failed, focus on the later.
570 // An update not making it to the relayer means it won't show up
571 // in other DCs (nor will consistent re-hashing see up-to-date values).
572 // On the other hand, if just the cache update failed, then it should
573 // eventually be applied by the relayer.
574 return $this->lastRelayError;
575 }
576
577 $code = $this->cache->getLastError();
578 switch ( $code ) {
579 case BagOStuff::ERR_NONE:
580 return self::ERR_NONE;
581 case BagOStuff::ERR_NO_RESPONSE:
582 return self::ERR_NO_RESPONSE;
583 case BagOStuff::ERR_UNREACHABLE:
584 return self::ERR_UNREACHABLE;
585 default:
586 return self::ERR_UNEXPECTED;
587 }
588 }
589
590 /**
591 * Clear the "last error" registry
592 */
593 final public function clearLastError() {
594 $this->cache->clearLastError();
595 $this->lastRelayError = self::ERR_NONE;
596 }
597
598 /**
599 * Do the actual async bus purge of a key
600 *
601 * This must set the key to "PURGED:<UNIX timestamp>"
602 *
603 * @param string $key Cache key
604 * @param integer $ttl How long to keep the tombstone [seconds]
605 * @return bool Success
606 */
607 protected function relayPurge( $key, $ttl ) {
608 $event = $this->cache->modifySimpleRelayEvent( array(
609 'cmd' => 'set',
610 'key' => $key,
611 'val' => 'PURGED:$UNIXTIME$',
612 'ttl' => max( $ttl, 1 ),
613 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
614 ) );
615
616 $ok = $this->relayer->notify( "{$this->pool}:purge", $event );
617 if ( !$ok ) {
618 $this->lastRelayError = self::ERR_RELAY;
619 }
620
621 return $ok;
622 }
623
624 /**
625 * Do the actual async bus delete of a key
626 *
627 * @param string $key Cache key
628 * @return bool Success
629 */
630 protected function relayDelete( $key ) {
631 $event = $this->cache->modifySimpleRelayEvent( array(
632 'cmd' => 'delete',
633 'key' => $key,
634 ) );
635
636 $ok = $this->relayer->notify( "{$this->pool}:purge", $event );
637 if ( !$ok ) {
638 $this->lastRelayError = self::ERR_RELAY;
639 }
640
641 return $ok;
642 }
643
644 /**
645 * Check if a key should be regenerated (using random probability)
646 *
647 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
648 * of returning true increases steadily from 0% to 100% as the $curTTL
649 * moves from $lowTTL to 0 seconds. This handles widely varying
650 * levels of cache access traffic.
651 *
652 * @param float $curTTL Approximate TTL left on the key if present
653 * @param float $lowTTL Consider a refresh when $curTTL is less than this
654 * @return bool
655 */
656 protected function worthRefresh( $curTTL, $lowTTL ) {
657 if ( $curTTL >= $lowTTL ) {
658 return false;
659 } elseif ( $curTTL <= 0 ) {
660 return true;
661 }
662
663 $chance = ( 1 - $curTTL / $lowTTL );
664
665 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
666 }
667
668 /**
669 * Do not use this method outside WANObjectCache
670 *
671 * @param mixed $value
672 * @param integer $ttl [0=forever]
673 * @return string
674 */
675 protected function wrap( $value, $ttl ) {
676 return array(
677 self::FLD_VERSION => self::VERSION,
678 self::FLD_VALUE => $value,
679 self::FLD_TTL => $ttl,
680 self::FLD_TIME => microtime( true )
681 );
682 }
683
684 /**
685 * Do not use this method outside WANObjectCache
686 *
687 * @param array|string|bool $wrapped
688 * @param float $now Unix Current timestamp (preferrable pre-query)
689 * @return array (mixed; false if absent/invalid, current time left)
690 */
691 protected function unwrap( $wrapped, $now ) {
692 // Check if the value is a tombstone
693 $purgeTimestamp = self::parsePurgeValue( $wrapped );
694 if ( is_float( $purgeTimestamp ) ) {
695 // Purged values should always have a negative current $ttl
696 $curTTL = min( -0.000001, $purgeTimestamp - $now );
697 return array( false, $curTTL );
698 }
699
700 if ( !is_array( $wrapped ) // not found
701 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
702 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
703 ) {
704 return array( false, null );
705 }
706
707 if ( $wrapped[self::FLD_TTL] > 0 ) {
708 // Get the approximate time left on the key
709 $age = $now - $wrapped[self::FLD_TIME];
710 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
711 } else {
712 // Key had no TTL, so the time left is unbounded
713 $curTTL = INF;
714 }
715
716 return array( $wrapped[self::FLD_VALUE], $curTTL );
717 }
718
719 /**
720 * @param array $keys
721 * @param string $prefix
722 * @return string[]
723 */
724 protected static function prefixCacheKeys( array $keys, $prefix ) {
725 $res = array();
726 foreach ( $keys as $key ) {
727 $res[] = $prefix . $key;
728 }
729
730 return $res;
731 }
732
733 /**
734 * @param string $value String like "PURGED:<timestamp>"
735 * @return float|bool UNIX timestamp or false on failure
736 */
737 protected static function parsePurgeValue( $value ) {
738 $m = array();
739 if ( is_string( $value ) &&
740 preg_match( '/^' . self::PURGE_VAL_PREFIX . '([^:]+)$/', $value, $m )
741 ) {
742 return (float)$m[1];
743 } else {
744 return false;
745 }
746 }
747 }