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