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