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