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