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