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