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