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