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