Merge "Use responsive CSS columns on Special:PrefixIndex and Special:AllPages"
[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. Special values are:
293 * - WANObjectCache::TTL_INDEFINITE: Cache forever
294 * @param array $opts Options map:
295 * - lag : Seconds of slave lag. Typically, this is either the slave lag
296 * before the data was read or, if applicable, the slave lag before
297 * the snapshot-isolated transaction the data was read from started.
298 * Default: 0 seconds
299 * - since : UNIX timestamp of the data in $value. Typically, this is either
300 * the current time the data was read or (if applicable) the time when
301 * the snapshot-isolated transaction the data was read from started.
302 * Default: 0 seconds
303 * - lockTSE : if excessive possible snapshot lag is detected,
304 * then stash the value into a temporary location
305 * with this TTL. This is only useful if the reads
306 * use getWithSetCallback() with "lockTSE" set.
307 * Default: WANObjectCache::TSE_NONE
308 * @return bool Success
309 */
310 final public function set( $key, $value, $ttl = 0, array $opts = array() ) {
311 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
312 $age = isset( $opts['since'] ) ? max( 0, microtime( true ) - $opts['since'] ) : 0;
313 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
314
315 if ( $lag > self::MAX_REPLICA_LAG ) {
316 // Too much lag detected; lower TTL so it converges faster
317 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
318 }
319
320 if ( $age > self::MAX_SNAPSHOT_LAG ) {
321 if ( $lockTSE >= 0 ) {
322 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
323 $this->cache->set( self::STASH_KEY_PREFIX . $key, $value, $tempTTL );
324 }
325
326 return true; // no-op the write for being unsafe
327 }
328
329 $wrapped = $this->wrap( $value, $ttl );
330
331 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
332 return ( is_string( $cWrapped ) )
333 ? false // key is tombstoned; do nothing
334 : $wrapped;
335 };
336
337 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl, 1 );
338 }
339
340 /**
341 * Purge a key from all datacenters
342 *
343 * This should only be called when the underlying data (being cached)
344 * changes in a significant way. This deletes the key and starts a hold-off
345 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
346 * This is done to avoid the following race condition:
347 * - a) Some DB data changes and delete() is called on a corresponding key
348 * - b) A request refills the key with a stale value from a lagged DB
349 * - c) The stale value is stuck there until the key is expired/evicted
350 *
351 * This is implemented by storing a special "tombstone" value at the cache
352 * key that this class recognizes; get() calls will return false for the key
353 * and any set() calls will refuse to replace tombstone values at the key.
354 * For this to always avoid stale value writes, the following must hold:
355 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
356 * - b) If lag is higher, the DB will have gone into read-only mode already
357 *
358 * Note that set() can also be lag-aware and lower the TTL if it's high.
359 *
360 * When using potentially long-running ACID transactions, a good pattern is
361 * to use a pre-commit hook to issue the delete. This means that immediately
362 * after commit, callers will see the tombstone in cache in the local datacenter
363 * and in the others upon relay. It also avoids the following race condition:
364 * - a) T1 begins, changes a row, and calls delete()
365 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
366 * - c) T2 starts, reads the row and calls set() due to a cache miss
367 * - d) T1 finally commits
368 * - e) Stale value is stuck in cache
369 *
370 * Example usage:
371 * @code
372 * $dbw->begin(); // start of request
373 * ... <execute some stuff> ...
374 * // Update the row in the DB
375 * $dbw->update( ... );
376 * $key = wfMemcKey( 'homes', $homeId );
377 * // Purge the corresponding cache entry just before committing
378 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
379 * $cache->delete( $key );
380 * } );
381 * ... <execute some stuff> ...
382 * $dbw->commit(); // end of request
383 * @endcode
384 *
385 * If called twice on the same key, then the last hold-off TTL takes
386 * precedence. For idempotence, the $ttl should not vary for different
387 * delete() calls on the same key. Also note that lowering $ttl reduces
388 * the effective range of the 'lockTSE' parameter to getWithSetCallback().
389 *
390 * @param string $key Cache key
391 * @param integer $ttl How long to block writes to the key [seconds]
392 * @return bool True if the item was purged or not found, false on failure
393 */
394 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
395 $key = self::VALUE_KEY_PREFIX . $key;
396 // Avoid indefinite key salting for sanity
397 $ttl = max( $ttl, 1 );
398 // Update the local datacenter immediately
399 $ok = $this->cache->set( $key, self::PURGE_VAL_PREFIX . microtime( true ), $ttl );
400 // Publish the purge to all datacenters
401 return $this->relayPurge( $key, $ttl ) && $ok;
402 }
403
404 /**
405 * Fetch the value of a timestamp "check" key
406 *
407 * The key will be *initialized* to the current time if not set,
408 * so only call this method if this behavior is actually desired
409 *
410 * The timestamp can be used to check whether a cached value is valid.
411 * Callers should not assume that this returns the same timestamp in
412 * all datacenters due to relay delays.
413 *
414 * The level of staleness can roughly be estimated from this key, but
415 * if the key was evicted from cache, such calculations may show the
416 * time since expiry as ~0 seconds.
417 *
418 * Note that "check" keys won't collide with other regular keys.
419 *
420 * @param string $key
421 * @return float UNIX timestamp of the key
422 */
423 final public function getCheckKeyTime( $key ) {
424 $key = self::TIME_KEY_PREFIX . $key;
425
426 $time = self::parsePurgeValue( $this->cache->get( $key ) );
427 if ( $time === false ) {
428 // Casting assures identical floats for the next getCheckKeyTime() calls
429 $time = (string)microtime( true );
430 $this->cache->add( $key, self::PURGE_VAL_PREFIX . $time, self::CHECK_KEY_TTL );
431 $time = (float)$time;
432 }
433
434 return $time;
435 }
436
437 /**
438 * Purge a "check" key from all datacenters, invalidating keys that use it
439 *
440 * This should only be called when the underlying data (being cached)
441 * changes in a significant way, and it is impractical to call delete()
442 * on all keys that should be changed. When get() is called on those
443 * keys, the relevant "check" keys must be supplied for this to work.
444 *
445 * The "check" key essentially represents a last-modified field.
446 * When touched, keys using it via get(), getMulti(), or getWithSetCallback()
447 * will be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
448 * by those methods to avoid race conditions where dependent keys get updated
449 * with stale values (e.g. from a DB slave).
450 *
451 * This is typically useful for keys with hardcoded names or in some cases
452 * dynamically generated names where a low number of combinations exist.
453 * When a few important keys get a large number of hits, a high cache
454 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
455 * method is less appropriate in such cases since the "time since expiry"
456 * cannot be inferred.
457 *
458 * Note that "check" keys won't collide with other regular keys.
459 *
460 * @see WANObjectCache::get()
461 * @see WANObjectCache::getWithSetCallback()
462 * @see WANObjectCache::resetCheckKey()
463 *
464 * @param string $key Cache key
465 * @return bool True if the item was purged or not found, false on failure
466 */
467 final public function touchCheckKey( $key ) {
468 $key = self::TIME_KEY_PREFIX . $key;
469 // Update the local datacenter immediately
470 $ok = $this->cache->set( $key,
471 self::PURGE_VAL_PREFIX . microtime( true ), self::CHECK_KEY_TTL );
472 // Publish the purge to all datacenters
473 return $this->relayPurge( $key, self::CHECK_KEY_TTL ) && $ok;
474 }
475
476 /**
477 * Delete a "check" key from all datacenters, invalidating keys that use it
478 *
479 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
480 * or getWithSetCallback() will be invalidated. The differences are:
481 * - a) The timestamp will be deleted from all caches and lazily
482 * re-initialized when accessed (rather than set everywhere)
483 * - b) Thus, dependent keys will be known to be invalid, but not
484 * for how long (they are treated as "just" purged), which
485 * effects any lockTSE logic in getWithSetCallback()
486 *
487 * The advantage is that this does not place high TTL keys on every cache
488 * server, making it better for code that will cache many different keys
489 * and either does not use lockTSE or uses a low enough TTL anyway.
490 *
491 * This is typically useful for keys with dynamically generated names
492 * where a high number of combinations exist.
493 *
494 * Note that "check" keys won't collide with other regular keys.
495 *
496 * @see WANObjectCache::get()
497 * @see WANObjectCache::getWithSetCallback()
498 * @see WANObjectCache::touchCheckKey()
499 *
500 * @param string $key Cache key
501 * @return bool True if the item was purged or not found, false on failure
502 */
503 final public function resetCheckKey( $key ) {
504 $key = self::TIME_KEY_PREFIX . $key;
505 // Update the local datacenter immediately
506 $ok = $this->cache->delete( $key );
507 // Publish the purge to all datacenters
508 return $this->relayDelete( $key ) && $ok;
509 }
510
511 /**
512 * Method to fetch/regenerate cache keys
513 *
514 * On cache miss, the key will be set to the callback result via set()
515 * (unless the callback returns false) and that result will be returned.
516 * The arguments supplied to the callback are:
517 * - $oldValue : current cache value or false if not present
518 * - &$ttl : a reference to the TTL which can be altered
519 * - &$setOpts : a reference to options for set() which can be altered
520 *
521 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
522 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
523 * value, but it can be used to maintain "most recent X" values that come from time or
524 * sequence based source data, provided that the "as of" id/time is tracked. Note that
525 * preemptive regeneration and $checkKeys can result in a non-false current value.
526 *
527 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
528 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
529 * regeneration will automatically be triggered using the callback.
530 *
531 * The simplest way to avoid stampedes for hot keys is to use
532 * the 'lockTSE' option in $opts. If cache purges are needed, also:
533 * - a) Pass $key into $checkKeys
534 * - b) Use touchCheckKey( $key ) instead of delete( $key )
535 *
536 * Example usage (typical key):
537 * @code
538 * $catInfo = $cache->getWithSetCallback(
539 * // Key to store the cached value under
540 * wfMemcKey( 'cat-attributes', $catId ),
541 * // Time-to-live (seconds)
542 * 60,
543 * // Function that derives the new key value
544 * function ( $oldValue, &$ttl, array &$setOpts ) {
545 * $dbr = wfGetDB( DB_SLAVE );
546 * // Account for any snapshot/slave lag
547 * $setOpts += Database::getCacheSetOptions( $dbr );
548 *
549 * return $dbr->selectRow( ... );
550 * }
551 * );
552 * @endcode
553 *
554 * Example usage (key that is expensive and hot):
555 * @code
556 * $catConfig = $cache->getWithSetCallback(
557 * // Key to store the cached value under
558 * wfMemcKey( 'site-cat-config' ),
559 * // Time-to-live (seconds)
560 * 86400,
561 * // Function that derives the new key value
562 * function ( $oldValue, &$ttl, array &$setOpts ) {
563 * $dbr = wfGetDB( DB_SLAVE );
564 * // Account for any snapshot/slave lag
565 * $setOpts += Database::getCacheSetOptions( $dbr );
566 *
567 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
568 * },
569 * array(
570 * // Calling touchCheckKey() on this key invalidates the cache
571 * 'checkKeys' => array( wfMemcKey( 'site-cat-config' ) ),
572 * // Try to only let one datacenter thread manage cache updates at a time
573 * 'lockTSE' => 30
574 * )
575 * );
576 * @endcode
577 *
578 * Example usage (key with dynamic dependencies):
579 * @code
580 * $catState = $cache->getWithSetCallback(
581 * // Key to store the cached value under
582 * wfMemcKey( 'cat-state', $cat->getId() ),
583 * // Time-to-live (seconds)
584 * 900,
585 * // Function that derives the new key value
586 * function ( $oldValue, &$ttl, array &$setOpts ) {
587 * // Determine new value from the DB
588 * $dbr = wfGetDB( DB_SLAVE );
589 * // Account for any snapshot/slave lag
590 * $setOpts += Database::getCacheSetOptions( $dbr );
591 *
592 * return CatState::newFromResults( $dbr->select( ... ) );
593 * },
594 * array(
595 * // The "check" keys that represent things the value depends on;
596 * // Calling touchCheckKey() on any of them invalidates the cache
597 * 'checkKeys' => array(
598 * wfMemcKey( 'sustenance-bowls', $cat->getRoomId() ),
599 * wfMemcKey( 'people-present', $cat->getHouseId() ),
600 * wfMemcKey( 'cat-laws', $cat->getCityId() ),
601 * )
602 * )
603 * );
604 * @endcode
605 *
606 * Example usage (hot key holding most recent 100 events):
607 * @code
608 * $lastCatActions = $cache->getWithSetCallback(
609 * // Key to store the cached value under
610 * wfMemcKey( 'cat-last-actions', 100 ),
611 * // Time-to-live (seconds)
612 * 10,
613 * // Function that derives the new key value
614 * function ( $oldValue, &$ttl, array &$setOpts ) {
615 * $dbr = wfGetDB( DB_SLAVE );
616 * // Account for any snapshot/slave lag
617 * $setOpts += Database::getCacheSetOptions( $dbr );
618 *
619 * // Start off with the last cached list
620 * $list = $oldValue ?: array();
621 * // Fetch the last 100 relevant rows in descending order;
622 * // only fetch rows newer than $list[0] to reduce scanning
623 * $rows = iterator_to_array( $dbr->select( ... ) );
624 * // Merge them and get the new "last 100" rows
625 * return array_slice( array_merge( $new, $list ), 0, 100 );
626 * },
627 * // Try to only let one datacenter thread manage cache updates at a time
628 * array( 'lockTSE' => 30 )
629 * );
630 * @endcode
631 *
632 * @see WANObjectCache::get()
633 * @see WANObjectCache::set()
634 *
635 * @param string $key Cache key
636 * @param integer $ttl Seconds to live for key updates. Special values are:
637 * - WANObjectCache::TTL_INDEFINITE: Cache forever
638 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
639 * @param callable $callback Value generation function
640 * @param array $opts Options map:
641 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
642 * touchCheckKey() or resetCheckKey() is called on any of these keys.
643 * - lowTTL: Consider pre-emptive updates when the current TTL (sec) of the key is less than
644 * this. It becomes more likely over time, becoming a certainty once the key is expired.
645 * Default: WANObjectCache::LOW_TTL seconds.
646 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
647 * ago, then try to have a single thread handle cache regeneration at any given time.
648 * Other threads will try to use stale values if possible. If, on miss, the time since
649 * expiration is low, the assumption is that the key is hot and that a stampede is worth
650 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
651 * higher this is set, the higher the worst-case staleness can be.
652 * Use WANObjectCache::TSE_NONE to disable this logic.
653 * Default: WANObjectCache::TSE_NONE.
654 * - pcTTL : process cache the value in this PHP instance with this TTL. This avoids
655 * network I/O when a key is read several times. This will not cache if the callback
656 * returns false however. Note that any purges will not be seen while process cached;
657 * since the callback should use slave DBs and they may be lagged or have snapshot
658 * isolation anyway, this should not typically matter.
659 * Default: WANObjectCache::TTL_UNCACHEABLE.
660 * @param array $oldOpts Unused (mentioned only to avoid PHPDoc warnings)
661 * @return mixed Value to use for the key
662 */
663 final public function getWithSetCallback(
664 $key, $ttl, $callback, array $opts = array(), $oldOpts = array()
665 ) {
666 // Back-compat with 1.26: Swap $ttl and $callback
667 if ( is_int( $callback ) ) {
668 $temp = $ttl;
669 $ttl = $callback;
670 $callback = $temp;
671 }
672 // Back-compat with 1.26: $checkKeys as separate parameter
673 if ( $oldOpts || ( is_array( $opts ) && isset( $opts[0] ) ) ) {
674 $checkKeys = $opts;
675 $opts = $oldOpts;
676 } else {
677 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : array();
678 }
679
680 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
681
682 // Try the process cache if enabled
683 $value = ( $pcTTL >= 0 ) ? $this->procCache->get( $key ) : false;
684
685 if ( $value === false ) {
686 // Fetch the value over the network
687 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $checkKeys, $opts );
688 // Update the process cache if enabled
689 if ( $pcTTL >= 0 && $value !== false ) {
690 $this->procCache->set( $key, $value, $pcTTL );
691 }
692 }
693
694 return $value;
695 }
696
697 /**
698 * Do the actual I/O for getWithSetCallback() when needed
699 *
700 * @see WANObjectCache::getWithSetCallback()
701 *
702 * @param string $key
703 * @param integer $ttl
704 * @param callback $callback
705 * @param array $checkKeys
706 * @param array $opts
707 * @return mixed
708 */
709 protected function doGetWithSetCallback(
710 $key, $ttl, $callback, array $checkKeys, array $opts
711 ) {
712 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
713 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
714
715 // Get the current key value
716 $curTTL = null;
717 $cValue = $this->get( $key, $curTTL, $checkKeys ); // current value
718 $value = $cValue; // return value
719
720 // Determine if a regeneration is desired
721 if ( $value !== false && $curTTL > 0 && !$this->worthRefresh( $curTTL, $lowTTL ) ) {
722 return $value;
723 }
724
725 // A deleted key with a negative TTL left must be tombstoned
726 $isTombstone = ( $curTTL !== null && $value === false );
727 // Assume a key is hot if requested soon after invalidation
728 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
729 // Decide whether a single thread should handle regenerations.
730 // This avoids stampedes when $checkKeys are bumped and when preemptive
731 // renegerations take too long. It also reduces regenerations while $key
732 // is tombstoned. This balances cache freshness with avoiding DB load.
733 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) );
734
735 $lockAcquired = false;
736 if ( $useMutex ) {
737 // Acquire a datacenter-local non-blocking lock
738 if ( $this->cache->lock( $key, 0, self::LOCK_TTL ) ) {
739 // Lock acquired; this thread should update the key
740 $lockAcquired = true;
741 } elseif ( $value !== false ) {
742 // If it cannot be acquired; then the stale value can be used
743 return $value;
744 } else {
745 // Use the stash value for tombstoned keys to reduce regeneration load.
746 // For hot keys, either another thread has the lock or the lock failed;
747 // use the stash value from the last thread that regenerated it.
748 $value = $this->cache->get( self::STASH_KEY_PREFIX . $key );
749 if ( $value !== false ) {
750 return $value;
751 }
752 }
753 }
754
755 if ( !is_callable( $callback ) ) {
756 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
757 }
758
759 // Generate the new value from the callback...
760 $setOpts = array();
761 $value = call_user_func_array( $callback, array( $cValue, &$ttl, &$setOpts ) );
762 // When delete() is called, writes are write-holed by the tombstone,
763 // so use a special stash key to pass the new value around threads.
764 if ( $useMutex && $value !== false && $ttl >= 0 ) {
765 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
766 $this->cache->set( self::STASH_KEY_PREFIX . $key, $value, $tempTTL );
767 }
768
769 if ( $lockAcquired ) {
770 $this->cache->unlock( $key );
771 }
772
773 if ( $value !== false && $ttl >= 0 ) {
774 // Update the cache; this will fail if the key is tombstoned
775 $setOpts['lockTSE'] = $lockTSE;
776 $this->set( $key, $value, $ttl, $setOpts );
777 }
778
779 return $value;
780 }
781
782 /**
783 * Get the "last error" registered; clearLastError() should be called manually
784 * @return int ERR_* constant for the "last error" registry
785 */
786 final public function getLastError() {
787 if ( $this->lastRelayError ) {
788 // If the cache and the relayer failed, focus on the later.
789 // An update not making it to the relayer means it won't show up
790 // in other DCs (nor will consistent re-hashing see up-to-date values).
791 // On the other hand, if just the cache update failed, then it should
792 // eventually be applied by the relayer.
793 return $this->lastRelayError;
794 }
795
796 $code = $this->cache->getLastError();
797 switch ( $code ) {
798 case BagOStuff::ERR_NONE:
799 return self::ERR_NONE;
800 case BagOStuff::ERR_NO_RESPONSE:
801 return self::ERR_NO_RESPONSE;
802 case BagOStuff::ERR_UNREACHABLE:
803 return self::ERR_UNREACHABLE;
804 default:
805 return self::ERR_UNEXPECTED;
806 }
807 }
808
809 /**
810 * Clear the "last error" registry
811 */
812 final public function clearLastError() {
813 $this->cache->clearLastError();
814 $this->lastRelayError = self::ERR_NONE;
815 }
816
817 /**
818 * Do the actual async bus purge of a key
819 *
820 * This must set the key to "PURGED:<UNIX timestamp>"
821 *
822 * @param string $key Cache key
823 * @param integer $ttl How long to keep the tombstone [seconds]
824 * @return bool Success
825 */
826 protected function relayPurge( $key, $ttl ) {
827 $event = $this->cache->modifySimpleRelayEvent( array(
828 'cmd' => 'set',
829 'key' => $key,
830 'val' => 'PURGED:$UNIXTIME$',
831 'ttl' => max( $ttl, 1 ),
832 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
833 ) );
834
835 $ok = $this->relayer->notify( "{$this->pool}:purge", $event );
836 if ( !$ok ) {
837 $this->lastRelayError = self::ERR_RELAY;
838 }
839
840 return $ok;
841 }
842
843 /**
844 * Do the actual async bus delete of a key
845 *
846 * @param string $key Cache key
847 * @return bool Success
848 */
849 protected function relayDelete( $key ) {
850 $event = $this->cache->modifySimpleRelayEvent( array(
851 'cmd' => 'delete',
852 'key' => $key,
853 ) );
854
855 $ok = $this->relayer->notify( "{$this->pool}:purge", $event );
856 if ( !$ok ) {
857 $this->lastRelayError = self::ERR_RELAY;
858 }
859
860 return $ok;
861 }
862
863 /**
864 * Check if a key should be regenerated (using random probability)
865 *
866 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
867 * of returning true increases steadily from 0% to 100% as the $curTTL
868 * moves from $lowTTL to 0 seconds. This handles widely varying
869 * levels of cache access traffic.
870 *
871 * @param float $curTTL Approximate TTL left on the key if present
872 * @param float $lowTTL Consider a refresh when $curTTL is less than this
873 * @return bool
874 */
875 protected function worthRefresh( $curTTL, $lowTTL ) {
876 if ( $curTTL >= $lowTTL ) {
877 return false;
878 } elseif ( $curTTL <= 0 ) {
879 return true;
880 }
881
882 $chance = ( 1 - $curTTL / $lowTTL );
883
884 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
885 }
886
887 /**
888 * Do not use this method outside WANObjectCache
889 *
890 * @param mixed $value
891 * @param integer $ttl [0=forever]
892 * @return string
893 */
894 protected function wrap( $value, $ttl ) {
895 return array(
896 self::FLD_VERSION => self::VERSION,
897 self::FLD_VALUE => $value,
898 self::FLD_TTL => $ttl,
899 self::FLD_TIME => microtime( true )
900 );
901 }
902
903 /**
904 * Do not use this method outside WANObjectCache
905 *
906 * @param array|string|bool $wrapped
907 * @param float $now Unix Current timestamp (preferrable pre-query)
908 * @return array (mixed; false if absent/invalid, current time left)
909 */
910 protected function unwrap( $wrapped, $now ) {
911 // Check if the value is a tombstone
912 $purgeTimestamp = self::parsePurgeValue( $wrapped );
913 if ( is_float( $purgeTimestamp ) ) {
914 // Purged values should always have a negative current $ttl
915 $curTTL = min( -0.000001, $purgeTimestamp - $now );
916 return array( false, $curTTL );
917 }
918
919 if ( !is_array( $wrapped ) // not found
920 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
921 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
922 ) {
923 return array( false, null );
924 }
925
926 if ( $wrapped[self::FLD_TTL] > 0 ) {
927 // Get the approximate time left on the key
928 $age = $now - $wrapped[self::FLD_TIME];
929 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
930 } else {
931 // Key had no TTL, so the time left is unbounded
932 $curTTL = INF;
933 }
934
935 return array( $wrapped[self::FLD_VALUE], $curTTL );
936 }
937
938 /**
939 * @param array $keys
940 * @param string $prefix
941 * @return string[]
942 */
943 protected static function prefixCacheKeys( array $keys, $prefix ) {
944 $res = array();
945 foreach ( $keys as $key ) {
946 $res[] = $prefix . $key;
947 }
948
949 return $res;
950 }
951
952 /**
953 * @param string $value String like "PURGED:<timestamp>"
954 * @return float|bool UNIX timestamp or false on failure
955 */
956 protected static function parsePurgeValue( $value ) {
957 $m = array();
958 if ( is_string( $value ) &&
959 preg_match( '/^' . self::PURGE_VAL_PREFIX . '([^:]+)$/', $value, $m )
960 ) {
961 return (float)$m[1];
962 } else {
963 return false;
964 }
965 }
966 }