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