5f6e3249dd3a3c8ee66832b9f6492a9d8bb0214e
[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 * The preferred way to do this logic is through getWithSetCallback().
37 * When querying the store on cache miss, the closest DB replica
38 * should be used. Try to avoid heavyweight DB master or quorum reads.
39 * When the source data changes, a purge method should be called.
40 * Since purges are expensive, they should be avoided. One can do so if:
41 * - a) The object cached is immutable; or
42 * - b) Validity is checked against the source after get(); or
43 * - c) Using a modest TTL is reasonably correct and performant
44 *
45 * The simplest purge method is delete().
46 *
47 * There are two supported ways to handle broadcasted operations:
48 * - a) Configure the 'purge' EventRelayer to point to a valid PubSub endpoint
49 * that has subscribed listeners on the cache servers applying the cache updates.
50 * - b) Ignore the 'purge' EventRelayer configuration (default is NullEventRelayer)
51 * and set up mcrouter as the underlying cache backend, using one of the memcached
52 * BagOStuff classes as 'cache'. Use OperationSelectorRoute in the mcrouter settings
53 * to configure 'set' and 'delete' operations to go to all DCs via AllAsyncRoute and
54 * configure other operations to go to the local DC via PoolRoute (for reference,
55 * see https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles).
56 *
57 * Broadcasted operations like delete() and touchCheckKey() are done asynchronously
58 * in all datacenters this way, though the local one should likely be near immediate.
59 *
60 * This means that callers in all datacenters may see older values for however many
61 * milliseconds that the purge took to reach that datacenter. As with any cache, this
62 * should not be relied on for cases where reads are used to determine writes to source
63 * (e.g. non-cache) data stores, except when reading immutable data.
64 *
65 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
66 * to avoid collisions with keys that are not wrapped as metadata arrays. The
67 * prefixes are as follows:
68 * - a) "WANCache:v" : used for regular value keys
69 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
70 * - c) "WANCache:t" : used for storing timestamp "check" keys
71 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
72 *
73 * @ingroup Cache
74 * @since 1.26
75 */
76 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
77 /** @var BagOStuff The local datacenter cache */
78 protected $cache;
79 /** @var HashBagOStuff[] Map of group PHP instance caches */
80 protected $processCaches = [];
81 /** @var string Purge channel name */
82 protected $purgeChannel;
83 /** @var EventRelayer Bus that handles purge broadcasts */
84 protected $purgeRelayer;
85 /** @var LoggerInterface */
86 protected $logger;
87
88 /** @var int ERR_* constant for the "last error" registry */
89 protected $lastRelayError = self::ERR_NONE;
90
91 /** Max time expected to pass between delete() and DB commit finishing */
92 const MAX_COMMIT_DELAY = 3;
93 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
94 const MAX_READ_LAG = 7;
95 /** Seconds to tombstone keys on delete() */
96 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
97
98 /** Seconds to keep dependency purge keys around */
99 const CHECK_KEY_TTL = self::TTL_YEAR;
100 /** Seconds to keep lock keys around */
101 const LOCK_TTL = 10;
102 /** Default remaining TTL at which to consider pre-emptive regeneration */
103 const LOW_TTL = 30;
104 /** Default time-since-expiry on a miss that makes a key "hot" */
105 const LOCK_TSE = 1;
106
107 /** Never consider performing "popularity" refreshes until a key reaches this age */
108 const AGE_NEW = 60;
109 /** The time length of the "popularity" refresh window for hot keys */
110 const HOT_TTR = 900;
111 /** Hits/second for a refresh to be expected within the "popularity" window */
112 const HIT_RATE_HIGH = 1;
113 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
114 const RAMPUP_TTL = 30;
115
116 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
117 const TTL_UNCACHEABLE = -1;
118 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
119 const TSE_NONE = -1;
120 /** Max TTL to store keys when a data sourced is lagged */
121 const TTL_LAGGED = 30;
122 /** Idiom for delete() for "no hold-off" */
123 const HOLDOFF_NONE = 0;
124 /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
125 const MIN_TIMESTAMP_NONE = 0.0;
126
127 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
128 const TINY_NEGATIVE = -0.000001;
129
130 /** Cache format version number */
131 const VERSION = 1;
132
133 const FLD_VERSION = 0; // key to cache version number
134 const FLD_VALUE = 1; // key to the cached value
135 const FLD_TTL = 2; // key to the original TTL
136 const FLD_TIME = 3; // key to the cache time
137 const FLD_FLAGS = 4; // key to the flags bitfield
138 const FLD_HOLDOFF = 5; // key to any hold-off TTL
139
140 /** @var integer Treat this value as expired-on-arrival */
141 const FLG_STALE = 1;
142
143 const ERR_NONE = 0; // no error
144 const ERR_NO_RESPONSE = 1; // no response
145 const ERR_UNREACHABLE = 2; // can't connect
146 const ERR_UNEXPECTED = 3; // response gave some error
147 const ERR_RELAY = 4; // relay broadcast failed
148
149 const VALUE_KEY_PREFIX = 'WANCache:v:';
150 const INTERIM_KEY_PREFIX = 'WANCache:i:';
151 const TIME_KEY_PREFIX = 'WANCache:t:';
152 const MUTEX_KEY_PREFIX = 'WANCache:m:';
153
154 const PURGE_VAL_PREFIX = 'PURGED:';
155
156 const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
157 const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
158
159 const PC_PRIMARY = 'primary:1000'; // process cache name and max key count
160
161 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
162
163 /**
164 * @param array $params
165 * - cache : BagOStuff object for a persistent cache
166 * - channels : Map of (action => channel string). Actions include "purge".
167 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
168 * - logger : LoggerInterface object
169 */
170 public function __construct( array $params ) {
171 $this->cache = $params['cache'];
172 $this->purgeChannel = isset( $params['channels']['purge'] )
173 ? $params['channels']['purge']
174 : self::DEFAULT_PURGE_CHANNEL;
175 $this->purgeRelayer = isset( $params['relayers']['purge'] )
176 ? $params['relayers']['purge']
177 : new EventRelayerNull( [] );
178 $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
179 }
180
181 public function setLogger( LoggerInterface $logger ) {
182 $this->logger = $logger;
183 }
184
185 /**
186 * Get an instance that wraps EmptyBagOStuff
187 *
188 * @return WANObjectCache
189 */
190 public static function newEmpty() {
191 return new self( [
192 'cache' => new EmptyBagOStuff(),
193 'pool' => 'empty',
194 'relayer' => new EventRelayerNull( [] )
195 ] );
196 }
197
198 /**
199 * Fetch the value of a key from cache
200 *
201 * If supplied, $curTTL is set to the remaining TTL (current time left):
202 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
203 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
204 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
205 * - d) null; if $key does not exist and is not tombstoned
206 *
207 * If a key is tombstoned, $curTTL will reflect the time since delete().
208 *
209 * The timestamp of $key will be checked against the last-purge timestamp
210 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
211 * initialized to the current timestamp. If any of $checkKeys have a timestamp
212 * greater than that of $key, then $curTTL will reflect how long ago $key
213 * became invalid. Callers can use $curTTL to know when the value is stale.
214 * The $checkKeys parameter allow mass invalidations by updating a single key:
215 * - a) Each "check" key represents "last purged" of some source data
216 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
217 * - c) When the source data that "check" keys represent changes,
218 * the touchCheckKey() method is called on them
219 *
220 * Source data entities might exists in a DB that uses snapshot isolation
221 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
222 * isolation can largely be maintained by doing the following:
223 * - a) Calling delete() on entity change *and* creation, before DB commit
224 * - b) Keeping transaction duration shorter than delete() hold-off TTL
225 *
226 * However, pre-snapshot values might still be seen if an update was made
227 * in a remote datacenter but the purge from delete() didn't relay yet.
228 *
229 * Consider using getWithSetCallback() instead of get() and set() cycles.
230 * That method has cache slam avoiding features for hot/expensive keys.
231 *
232 * @param string $key Cache key
233 * @param mixed $curTTL Approximate TTL left on the key if present/tombstoned [returned]
234 * @param array $checkKeys List of "check" keys
235 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
236 * @return mixed Value of cache key or false on failure
237 */
238 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
239 $curTTLs = [];
240 $asOfs = [];
241 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
242 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
243 $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null;
244
245 return isset( $values[$key] ) ? $values[$key] : false;
246 }
247
248 /**
249 * Fetch the value of several keys from cache
250 *
251 * @see WANObjectCache::get()
252 *
253 * @param array $keys List of cache keys
254 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
255 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
256 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
257 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
258 * @return array Map of (key => value) for keys that exist
259 */
260 final public function getMulti(
261 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
262 ) {
263 $result = [];
264 $curTTLs = [];
265 $asOfs = [];
266
267 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
268 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
269
270 $checkKeysForAll = [];
271 $checkKeysByKey = [];
272 $checkKeysFlat = [];
273 foreach ( $checkKeys as $i => $keys ) {
274 $prefixed = self::prefixCacheKeys( (array)$keys, self::TIME_KEY_PREFIX );
275 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
276 // Is this check keys for a specific cache key, or for all keys being fetched?
277 if ( is_int( $i ) ) {
278 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
279 } else {
280 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
281 ? array_merge( $checkKeysByKey[$i], $prefixed )
282 : $prefixed;
283 }
284 }
285
286 // Fetch all of the raw values
287 $wrappedValues = $this->cache->getMulti( array_merge( $valueKeys, $checkKeysFlat ) );
288 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
289 $now = microtime( true );
290
291 // Collect timestamps from all "check" keys
292 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
293 $purgeValuesByKey = [];
294 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
295 $purgeValuesByKey[$cacheKey] =
296 $this->processCheckKeys( $checks, $wrappedValues, $now );
297 }
298
299 // Get the main cache value for each key and validate them
300 foreach ( $valueKeys as $vKey ) {
301 if ( !isset( $wrappedValues[$vKey] ) ) {
302 continue; // not found
303 }
304
305 $key = substr( $vKey, $vPrefixLen ); // unprefix
306
307 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
308 if ( $value !== false ) {
309 $result[$key] = $value;
310
311 // Force dependant keys to be invalid for a while after purging
312 // to reduce race conditions involving stale data getting cached
313 $purgeValues = $purgeValuesForAll;
314 if ( isset( $purgeValuesByKey[$key] ) ) {
315 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
316 }
317 foreach ( $purgeValues as $purge ) {
318 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
319 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
320 // How long ago this value was expired by *this* check key
321 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
322 // How long ago this value was expired by *any* known check key
323 $curTTL = min( $curTTL, $ago );
324 }
325 }
326 }
327 $curTTLs[$key] = $curTTL;
328 $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
329 }
330
331 return $result;
332 }
333
334 /**
335 * @since 1.27
336 * @param array $timeKeys List of prefixed time check keys
337 * @param array $wrappedValues
338 * @param float $now
339 * @return array List of purge value arrays
340 */
341 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
342 $purgeValues = [];
343 foreach ( $timeKeys as $timeKey ) {
344 $purge = isset( $wrappedValues[$timeKey] )
345 ? self::parsePurgeValue( $wrappedValues[$timeKey] )
346 : false;
347 if ( $purge === false ) {
348 // Key is not set or invalid; regenerate
349 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
350 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
351 $purge = self::parsePurgeValue( $newVal );
352 }
353 $purgeValues[] = $purge;
354 }
355 return $purgeValues;
356 }
357
358 /**
359 * Set the value of a key in cache
360 *
361 * Simply calling this method when source data changes is not valid because
362 * the changes do not replicate to the other WAN sites. In that case, delete()
363 * should be used instead. This method is intended for use on cache misses.
364 *
365 * If the data was read from a snapshot-isolated transactions (e.g. the default
366 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
367 * - a) T1 starts
368 * - b) T2 updates a row, calls delete(), and commits
369 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
370 * - d) T1 reads the row and calls set() due to a cache miss
371 * - e) Stale value is stuck in cache
372 *
373 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
374 *
375 * Example usage:
376 * @code
377 * $dbr = wfGetDB( DB_REPLICA );
378 * $setOpts = Database::getCacheSetOptions( $dbr );
379 * // Fetch the row from the DB
380 * $row = $dbr->selectRow( ... );
381 * $key = $cache->makeKey( 'building', $buildingId );
382 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
383 * @endcode
384 *
385 * @param string $key Cache key
386 * @param mixed $value
387 * @param integer $ttl Seconds to live. Special values are:
388 * - WANObjectCache::TTL_INDEFINITE: Cache forever
389 * @param array $opts Options map:
390 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
391 * before the data was read or, if applicable, the replica DB lag before
392 * the snapshot-isolated transaction the data was read from started.
393 * Use false to indicate that replication is not running.
394 * Default: 0 seconds
395 * - since : UNIX timestamp of the data in $value. Typically, this is either
396 * the current time the data was read or (if applicable) the time when
397 * the snapshot-isolated transaction the data was read from started.
398 * Default: 0 seconds
399 * - pending : Whether this data is possibly from an uncommitted write transaction.
400 * Generally, other threads should not see values from the future and
401 * they certainly should not see ones that ended up getting rolled back.
402 * Default: false
403 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
404 * with this TTL and flag it as stale. This is only useful if the reads for
405 * this key use getWithSetCallback() with "lockTSE" set.
406 * Default: WANObjectCache::TSE_NONE
407 * - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
408 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
409 * will call the regeneration callback in such cases, passing in the old value
410 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
411 * on the old value's as-of time when it is verified as still being correct.
412 * Default: 0.
413 * @note Options added in 1.28: staleTTL
414 * @return bool Success
415 */
416 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
417 $now = microtime( true );
418 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
419 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
420 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
421 $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : 0;
422
423 // Do not cache potentially uncommitted data as it might get rolled back
424 if ( !empty( $opts['pending'] ) ) {
425 $this->logger->info( "Rejected set() for $key due to pending writes." );
426
427 return true; // no-op the write for being unsafe
428 }
429
430 $wrapExtra = []; // additional wrapped value fields
431 // Check if there's a risk of writing stale data after the purge tombstone expired
432 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
433 // Case A: read lag with "lockTSE"; save but record value as stale
434 if ( $lockTSE >= 0 ) {
435 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
436 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
437 // Case B: any long-running transaction; ignore this set()
438 } elseif ( $age > self::MAX_READ_LAG ) {
439 $this->logger->warning( "Rejected set() for $key due to snapshot lag." );
440
441 return true; // no-op the write for being unsafe
442 // Case C: high replication lag; lower TTL instead of ignoring all set()s
443 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
444 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
445 $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
446 // Case D: medium length request with medium replication lag; ignore this set()
447 } else {
448 $this->logger->warning( "Rejected set() for $key due to high read lag." );
449
450 return true; // no-op the write for being unsafe
451 }
452 }
453
454 // Wrap that value with time/TTL/version metadata
455 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
456
457 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
458 return ( is_string( $cWrapped ) )
459 ? false // key is tombstoned; do nothing
460 : $wrapped;
461 };
462
463 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl + $staleTTL, 1 );
464 }
465
466 /**
467 * Purge a key from all datacenters
468 *
469 * This should only be called when the underlying data (being cached)
470 * changes in a significant way. This deletes the key and starts a hold-off
471 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
472 * This is done to avoid the following race condition:
473 * - a) Some DB data changes and delete() is called on a corresponding key
474 * - b) A request refills the key with a stale value from a lagged DB
475 * - c) The stale value is stuck there until the key is expired/evicted
476 *
477 * This is implemented by storing a special "tombstone" value at the cache
478 * key that this class recognizes; get() calls will return false for the key
479 * and any set() calls will refuse to replace tombstone values at the key.
480 * For this to always avoid stale value writes, the following must hold:
481 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
482 * - b) If lag is higher, the DB will have gone into read-only mode already
483 *
484 * Note that set() can also be lag-aware and lower the TTL if it's high.
485 *
486 * When using potentially long-running ACID transactions, a good pattern is
487 * to use a pre-commit hook to issue the delete. This means that immediately
488 * after commit, callers will see the tombstone in cache upon purge relay.
489 * It also avoids the following race condition:
490 * - a) T1 begins, changes a row, and calls delete()
491 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
492 * - c) T2 starts, reads the row and calls set() due to a cache miss
493 * - d) T1 finally commits
494 * - e) Stale value is stuck in cache
495 *
496 * Example usage:
497 * @code
498 * $dbw->startAtomic( __METHOD__ ); // start of request
499 * ... <execute some stuff> ...
500 * // Update the row in the DB
501 * $dbw->update( ... );
502 * $key = $cache->makeKey( 'homes', $homeId );
503 * // Purge the corresponding cache entry just before committing
504 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
505 * $cache->delete( $key );
506 * } );
507 * ... <execute some stuff> ...
508 * $dbw->endAtomic( __METHOD__ ); // end of request
509 * @endcode
510 *
511 * The $ttl parameter can be used when purging values that have not actually changed
512 * recently. For example, a cleanup script to purge cache entries does not really need
513 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
514 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
515 *
516 * If called twice on the same key, then the last hold-off TTL takes precedence. For
517 * idempotence, the $ttl should not vary for different delete() calls on the same key.
518 *
519 * @param string $key Cache key
520 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
521 * @return bool True if the item was purged or not found, false on failure
522 */
523 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
524 $key = self::VALUE_KEY_PREFIX . $key;
525
526 if ( $ttl <= 0 ) {
527 // Publish the purge to all datacenters
528 $ok = $this->relayDelete( $key );
529 } else {
530 // Publish the purge to all datacenters
531 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE );
532 }
533
534 return $ok;
535 }
536
537 /**
538 * Fetch the value of a timestamp "check" key
539 *
540 * The key will be *initialized* to the current time if not set,
541 * so only call this method if this behavior is actually desired
542 *
543 * The timestamp can be used to check whether a cached value is valid.
544 * Callers should not assume that this returns the same timestamp in
545 * all datacenters due to relay delays.
546 *
547 * The level of staleness can roughly be estimated from this key, but
548 * if the key was evicted from cache, such calculations may show the
549 * time since expiry as ~0 seconds.
550 *
551 * Note that "check" keys won't collide with other regular keys.
552 *
553 * @param string $key
554 * @return float UNIX timestamp of the check key
555 */
556 final public function getCheckKeyTime( $key ) {
557 $key = self::TIME_KEY_PREFIX . $key;
558
559 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
560 if ( $purge !== false ) {
561 $time = $purge[self::FLD_TIME];
562 } else {
563 // Casting assures identical floats for the next getCheckKeyTime() calls
564 $now = (string)microtime( true );
565 $this->cache->add( $key,
566 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
567 self::CHECK_KEY_TTL
568 );
569 $time = (float)$now;
570 }
571
572 return $time;
573 }
574
575 /**
576 * Purge a "check" key from all datacenters, invalidating keys that use it
577 *
578 * This should only be called when the underlying data (being cached)
579 * changes in a significant way, and it is impractical to call delete()
580 * on all keys that should be changed. When get() is called on those
581 * keys, the relevant "check" keys must be supplied for this to work.
582 *
583 * The "check" key essentially represents a last-modified field.
584 * When touched, the field will be updated on all cache servers.
585 * Keys using it via get(), getMulti(), or getWithSetCallback() will
586 * be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
587 * by those methods to avoid race conditions where dependent keys get updated
588 * with stale values (e.g. from a DB replica DB).
589 *
590 * This is typically useful for keys with hardcoded names or in some cases
591 * dynamically generated names where a low number of combinations exist.
592 * When a few important keys get a large number of hits, a high cache
593 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
594 * method is less appropriate in such cases since the "time since expiry"
595 * cannot be inferred, causing any get() after the reset to treat the key
596 * as being "hot", resulting in more stale value usage.
597 *
598 * Note that "check" keys won't collide with other regular keys.
599 *
600 * @see WANObjectCache::get()
601 * @see WANObjectCache::getWithSetCallback()
602 * @see WANObjectCache::resetCheckKey()
603 *
604 * @param string $key Cache key
605 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
606 * @return bool True if the item was purged or not found, false on failure
607 */
608 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
609 // Publish the purge to all datacenters
610 return $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
611 }
612
613 /**
614 * Delete a "check" key from all datacenters, invalidating keys that use it
615 *
616 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
617 * or getWithSetCallback() will be invalidated. The differences are:
618 * - a) The "check" key will be deleted from all caches and lazily
619 * re-initialized when accessed (rather than set everywhere)
620 * - b) Thus, dependent keys will be known to be invalid, but not
621 * for how long (they are treated as "just" purged), which
622 * effects any lockTSE logic in getWithSetCallback()
623 * - c) Since "check" keys are initialized only on the server the key hashes
624 * to, any temporary ejection of that server will cause the value to be
625 * seen as purged as a new server will initialize the "check" key.
626 *
627 * The advantage is that this does not place high TTL keys on every cache
628 * server, making it better for code that will cache many different keys
629 * and either does not use lockTSE or uses a low enough TTL anyway.
630 *
631 * This is typically useful for keys with dynamically generated names
632 * where a high number of combinations exist.
633 *
634 * Note that "check" keys won't collide with other regular keys.
635 *
636 * @see WANObjectCache::get()
637 * @see WANObjectCache::getWithSetCallback()
638 * @see WANObjectCache::touchCheckKey()
639 *
640 * @param string $key Cache key
641 * @return bool True if the item was purged or not found, false on failure
642 */
643 final public function resetCheckKey( $key ) {
644 // Publish the purge to all datacenters
645 return $this->relayDelete( self::TIME_KEY_PREFIX . $key );
646 }
647
648 /**
649 * Method to fetch/regenerate cache keys
650 *
651 * On cache miss, the key will be set to the callback result via set()
652 * (unless the callback returns false) and that result will be returned.
653 * The arguments supplied to the callback are:
654 * - $oldValue : current cache value or false if not present
655 * - &$ttl : a reference to the TTL which can be altered
656 * - &$setOpts : a reference to options for set() which can be altered
657 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
658 *
659 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
660 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
661 * value, but it can be used to maintain "most recent X" values that come from time or
662 * sequence based source data, provided that the "as of" id/time is tracked. Note that
663 * preemptive regeneration and $checkKeys can result in a non-false current value.
664 *
665 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
666 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
667 * regeneration will automatically be triggered using the callback.
668 *
669 * The simplest way to avoid stampedes for hot keys is to use
670 * the 'lockTSE' option in $opts. If cache purges are needed, also:
671 * - a) Pass $key into $checkKeys
672 * - b) Use touchCheckKey( $key ) instead of delete( $key )
673 *
674 * Example usage (typical key):
675 * @code
676 * $catInfo = $cache->getWithSetCallback(
677 * // Key to store the cached value under
678 * $cache->makeKey( 'cat-attributes', $catId ),
679 * // Time-to-live (in seconds)
680 * $cache::TTL_MINUTE,
681 * // Function that derives the new key value
682 * function ( $oldValue, &$ttl, array &$setOpts ) {
683 * $dbr = wfGetDB( DB_REPLICA );
684 * // Account for any snapshot/replica DB lag
685 * $setOpts += Database::getCacheSetOptions( $dbr );
686 *
687 * return $dbr->selectRow( ... );
688 * }
689 * );
690 * @endcode
691 *
692 * Example usage (key that is expensive and hot):
693 * @code
694 * $catConfig = $cache->getWithSetCallback(
695 * // Key to store the cached value under
696 * $cache->makeKey( 'site-cat-config' ),
697 * // Time-to-live (in seconds)
698 * $cache::TTL_DAY,
699 * // Function that derives the new key value
700 * function ( $oldValue, &$ttl, array &$setOpts ) {
701 * $dbr = wfGetDB( DB_REPLICA );
702 * // Account for any snapshot/replica DB lag
703 * $setOpts += Database::getCacheSetOptions( $dbr );
704 *
705 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
706 * },
707 * [
708 * // Calling touchCheckKey() on this key invalidates the cache
709 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
710 * // Try to only let one datacenter thread manage cache updates at a time
711 * 'lockTSE' => 30,
712 * // Avoid querying cache servers multiple times in a web request
713 * 'pcTTL' => $cache::TTL_PROC_LONG
714 * ]
715 * );
716 * @endcode
717 *
718 * Example usage (key with dynamic dependencies):
719 * @code
720 * $catState = $cache->getWithSetCallback(
721 * // Key to store the cached value under
722 * $cache->makeKey( 'cat-state', $cat->getId() ),
723 * // Time-to-live (seconds)
724 * $cache::TTL_HOUR,
725 * // Function that derives the new key value
726 * function ( $oldValue, &$ttl, array &$setOpts ) {
727 * // Determine new value from the DB
728 * $dbr = wfGetDB( DB_REPLICA );
729 * // Account for any snapshot/replica DB lag
730 * $setOpts += Database::getCacheSetOptions( $dbr );
731 *
732 * return CatState::newFromResults( $dbr->select( ... ) );
733 * },
734 * [
735 * // The "check" keys that represent things the value depends on;
736 * // Calling touchCheckKey() on any of them invalidates the cache
737 * 'checkKeys' => [
738 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
739 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
740 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
741 * ]
742 * ]
743 * );
744 * @endcode
745 *
746 * Example usage (hot key holding most recent 100 events):
747 * @code
748 * $lastCatActions = $cache->getWithSetCallback(
749 * // Key to store the cached value under
750 * $cache->makeKey( 'cat-last-actions', 100 ),
751 * // Time-to-live (in seconds)
752 * 10,
753 * // Function that derives the new key value
754 * function ( $oldValue, &$ttl, array &$setOpts ) {
755 * $dbr = wfGetDB( DB_REPLICA );
756 * // Account for any snapshot/replica DB lag
757 * $setOpts += Database::getCacheSetOptions( $dbr );
758 *
759 * // Start off with the last cached list
760 * $list = $oldValue ?: [];
761 * // Fetch the last 100 relevant rows in descending order;
762 * // only fetch rows newer than $list[0] to reduce scanning
763 * $rows = iterator_to_array( $dbr->select( ... ) );
764 * // Merge them and get the new "last 100" rows
765 * return array_slice( array_merge( $new, $list ), 0, 100 );
766 * },
767 * [
768 * // Try to only let one datacenter thread manage cache updates at a time
769 * 'lockTSE' => 30,
770 * // Use a magic value when no cache value is ready rather than stampeding
771 * 'busyValue' => 'computing'
772 * ]
773 * );
774 * @endcode
775 *
776 * @see WANObjectCache::get()
777 * @see WANObjectCache::set()
778 *
779 * @param string $key Cache key
780 * @param integer $ttl Seconds to live for key updates. Special values are:
781 * - WANObjectCache::TTL_INDEFINITE: Cache forever
782 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
783 * @param callable $callback Value generation function
784 * @param array $opts Options map:
785 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
786 * touchCheckKey() or resetCheckKey() is called on any of these keys.
787 * Default: [].
788 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
789 * ago, then try to have a single thread handle cache regeneration at any given time.
790 * Other threads will try to use stale values if possible. If, on miss, the time since
791 * expiration is low, the assumption is that the key is hot and that a stampede is worth
792 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
793 * higher this is set, the higher the worst-case staleness can be.
794 * Use WANObjectCache::TSE_NONE to disable this logic.
795 * Default: WANObjectCache::TSE_NONE.
796 * - busyValue: If no value exists and another thread is currently regenerating it, use this
797 * as a fallback value (or a callback to generate such a value). This assures that cache
798 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
799 * against cache regeneration becoming very slow for some reason (greater than the TTL).
800 * Default: null.
801 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
802 * network I/O when a key is read several times. This will not cache when the callback
803 * returns false, however. Note that any purges will not be seen while process cached;
804 * since the callback should use replica DBs and they may be lagged or have snapshot
805 * isolation anyway, this should not typically matter.
806 * Default: WANObjectCache::TTL_UNCACHEABLE.
807 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
808 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
809 * large values, small yet numerous values, or some values with a high cost of eviction.
810 * It is generally preferable to use a class constant when setting this value.
811 * This has no effect unless pcTTL is used.
812 * Default: WANObjectCache::PC_PRIMARY.
813 * - version: Integer version number. This allows for callers to make breaking changes to
814 * how values are stored while maintaining compatability and correct cache purges. New
815 * versions are stored alongside older versions concurrently. Avoid storing class objects
816 * however, as this reduces compatibility (due to serialization).
817 * Default: null.
818 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
819 * This is useful if the source of a key is suspected of having possibly changed
820 * recently, and the caller wants any such changes to be reflected.
821 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
822 * - hotTTR: Expected time-till-refresh for keys that average ~1 hit/second.
823 * This should be greater than "ageNew". Keys with higher hit rates will regenerate
824 * more often. This is useful when a popular key is changed but the cache purge was
825 * delayed or lost. Seldom used keys are rarely affected by this setting, unless an
826 * extremely low "hotTTR" value is passed in.
827 * Default: WANObjectCache::HOT_TTR.
828 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
829 * than this. It becomes more likely over time, becoming certain once the key is expired.
830 * Default: WANObjectCache::LOW_TTL.
831 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
832 * Default: WANObjectCache::AGE_NEW.
833 * @return mixed Value found or written to the key
834 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
835 * @note Callable type hints are not used to avoid class-autoloading
836 */
837 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
838 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
839
840 // Try the process cache if enabled
841 if ( $pcTTL >= 0 ) {
842 $group = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY;
843 $procCache = $this->getProcessCache( $group );
844 $value = $procCache->get( $key );
845 } else {
846 $procCache = false;
847 $value = false;
848 }
849
850 if ( $value === false ) {
851 // Fetch the value over the network
852 if ( isset( $opts['version'] ) ) {
853 $version = $opts['version'];
854 $asOf = null;
855 $cur = $this->doGetWithSetCallback(
856 $key,
857 $ttl,
858 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
859 use ( $callback, $version ) {
860 if ( is_array( $oldValue )
861 && array_key_exists( self::VFLD_DATA, $oldValue )
862 ) {
863 $oldData = $oldValue[self::VFLD_DATA];
864 } else {
865 // VFLD_DATA is not set if an old, unversioned, key is present
866 $oldData = false;
867 }
868
869 return [
870 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
871 self::VFLD_VERSION => $version
872 ];
873 },
874 $opts,
875 $asOf
876 );
877 if ( $cur[self::VFLD_VERSION] === $version ) {
878 // Value created or existed before with version; use it
879 $value = $cur[self::VFLD_DATA];
880 } else {
881 // Value existed before with a different version; use variant key.
882 // Reflect purges to $key by requiring that this key value be newer.
883 $value = $this->doGetWithSetCallback(
884 'cache-variant:' . md5( $key ) . ":$version",
885 $ttl,
886 $callback,
887 // Regenerate value if not newer than $key
888 [ 'version' => null, 'minAsOf' => $asOf ] + $opts
889 );
890 }
891 } else {
892 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
893 }
894
895 // Update the process cache if enabled
896 if ( $procCache && $value !== false ) {
897 $procCache->set( $key, $value, $pcTTL );
898 }
899 }
900
901 return $value;
902 }
903
904 /**
905 * Do the actual I/O for getWithSetCallback() when needed
906 *
907 * @see WANObjectCache::getWithSetCallback()
908 *
909 * @param string $key
910 * @param integer $ttl
911 * @param callback $callback
912 * @param array $opts Options map for getWithSetCallback()
913 * @param float &$asOf Cache generation timestamp of returned value [returned]
914 * @return mixed
915 * @note Callable type hints are not used to avoid class-autoloading
916 */
917 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
918 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
919 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
920 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
921 $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
922 $popWindow = isset( $opts['hotTTR'] ) ? $opts['hotTTR'] : self::HOT_TTR;
923 $ageNew = isset( $opts['ageNew'] ) ? $opts['ageNew'] : self::AGE_NEW;
924 $minTime = isset( $opts['minAsOf'] ) ? $opts['minAsOf'] : self::MIN_TIMESTAMP_NONE;
925 $versioned = isset( $opts['version'] );
926
927 // Get the current key value
928 $curTTL = null;
929 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
930 $value = $cValue; // return value
931
932 // Determine if a regeneration is desired
933 if ( $value !== false
934 && $curTTL > 0
935 && $this->isValid( $value, $versioned, $asOf, $minTime )
936 && !$this->worthRefreshExpiring( $curTTL, $lowTTL )
937 && !$this->worthRefreshPopular( $asOf, $ageNew, $popWindow )
938 ) {
939 return $value;
940 }
941
942 // A deleted key with a negative TTL left must be tombstoned
943 $isTombstone = ( $curTTL !== null && $value === false );
944 // Assume a key is hot if requested soon after invalidation
945 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
946 // Use the mutex if there is no value and a busy fallback is given
947 $checkBusy = ( $busyValue !== null && $value === false );
948 // Decide whether a single thread should handle regenerations.
949 // This avoids stampedes when $checkKeys are bumped and when preemptive
950 // renegerations take too long. It also reduces regenerations while $key
951 // is tombstoned. This balances cache freshness with avoiding DB load.
952 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
953
954 $lockAcquired = false;
955 if ( $useMutex ) {
956 // Acquire a datacenter-local non-blocking lock
957 if ( $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
958 // Lock acquired; this thread should update the key
959 $lockAcquired = true;
960 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
961 // If it cannot be acquired; then the stale value can be used
962 return $value;
963 } else {
964 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
965 // For hot keys, either another thread has the lock or the lock failed;
966 // use the INTERIM value from the last thread that regenerated it.
967 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
968 list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
969 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
970 $asOf = $wrapped[self::FLD_TIME];
971
972 return $value;
973 }
974 // Use the busy fallback value if nothing else
975 if ( $busyValue !== null ) {
976 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
977 }
978 }
979 }
980
981 if ( !is_callable( $callback ) ) {
982 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
983 }
984
985 // Generate the new value from the callback...
986 $setOpts = [];
987 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
988 // When delete() is called, writes are write-holed by the tombstone,
989 // so use a special INTERIM key to pass the new value around threads.
990 if ( ( $isTombstone && $lockTSE > 0 ) && $value !== false && $ttl >= 0 ) {
991 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
992 $newAsOf = microtime( true );
993 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
994 // Avoid using set() to avoid pointless mcrouter broadcasting
995 $this->cache->merge(
996 self::INTERIM_KEY_PREFIX . $key,
997 function () use ( $wrapped ) {
998 return $wrapped;
999 },
1000 $tempTTL,
1001 1
1002 );
1003 }
1004
1005 if ( $value !== false && $ttl >= 0 ) {
1006 // Update the cache; this will fail if the key is tombstoned
1007 $setOpts['lockTSE'] = $lockTSE;
1008 $this->set( $key, $value, $ttl, $setOpts );
1009 }
1010
1011 if ( $lockAcquired ) {
1012 // Avoid using delete() to avoid pointless mcrouter broadcasting
1013 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, 1 );
1014 }
1015
1016 return $value;
1017 }
1018
1019 /**
1020 * @see BagOStuff::makeKey()
1021 * @param string ... Key component
1022 * @return string
1023 * @since 1.27
1024 */
1025 public function makeKey() {
1026 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1027 }
1028
1029 /**
1030 * @see BagOStuff::makeGlobalKey()
1031 * @param string ... Key component
1032 * @return string
1033 * @since 1.27
1034 */
1035 public function makeGlobalKey() {
1036 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1037 }
1038
1039 /**
1040 * Get the "last error" registered; clearLastError() should be called manually
1041 * @return int ERR_* class constant for the "last error" registry
1042 */
1043 final public function getLastError() {
1044 if ( $this->lastRelayError ) {
1045 // If the cache and the relayer failed, focus on the latter.
1046 // An update not making it to the relayer means it won't show up
1047 // in other DCs (nor will consistent re-hashing see up-to-date values).
1048 // On the other hand, if just the cache update failed, then it should
1049 // eventually be applied by the relayer.
1050 return $this->lastRelayError;
1051 }
1052
1053 $code = $this->cache->getLastError();
1054 switch ( $code ) {
1055 case BagOStuff::ERR_NONE:
1056 return self::ERR_NONE;
1057 case BagOStuff::ERR_NO_RESPONSE:
1058 return self::ERR_NO_RESPONSE;
1059 case BagOStuff::ERR_UNREACHABLE:
1060 return self::ERR_UNREACHABLE;
1061 default:
1062 return self::ERR_UNEXPECTED;
1063 }
1064 }
1065
1066 /**
1067 * Clear the "last error" registry
1068 */
1069 final public function clearLastError() {
1070 $this->cache->clearLastError();
1071 $this->lastRelayError = self::ERR_NONE;
1072 }
1073
1074 /**
1075 * Clear the in-process caches; useful for testing
1076 *
1077 * @since 1.27
1078 */
1079 public function clearProcessCache() {
1080 $this->processCaches = [];
1081 }
1082
1083 /**
1084 * @param integer $flag ATTR_* class constant
1085 * @return integer QOS_* class constant
1086 * @since 1.28
1087 */
1088 public function getQoS( $flag ) {
1089 return $this->cache->getQoS( $flag );
1090 }
1091
1092 /**
1093 * Get a TTL that is higher for objects that have not changed recently
1094 *
1095 * This is useful for keys that get explicit purges and DB or purge relay
1096 * lag is a potential concern (especially how it interacts with CDN cache)
1097 *
1098 * Example usage:
1099 * @code
1100 * // Last-modified time of page
1101 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1102 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1103 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1104 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1105 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1106 * @endcode
1107 *
1108 * @param integer|float $mtime UNIX timestamp
1109 * @param integer $maxTTL Maximum TTL (seconds)
1110 * @param integer $minTTL Minimum TTL (seconds); Default: 30
1111 * @param float $factor Value in the range (0,1); Default: .2
1112 * @return integer Adaptive TTL
1113 * @since 1.28
1114 */
1115 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = .2 ) {
1116 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
1117 $mtime = (int)$mtime; // handle fractional seconds and string integers
1118 }
1119
1120 if ( !is_int( $mtime ) || $mtime <= 0 ) {
1121 return $minTTL; // no last-modified time provided
1122 }
1123
1124 $age = time() - $mtime;
1125
1126 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1127 }
1128
1129 /**
1130 * Do the actual async bus purge of a key
1131 *
1132 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1133 *
1134 * @param string $key Cache key
1135 * @param integer $ttl How long to keep the tombstone [seconds]
1136 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1137 * @return bool Success
1138 */
1139 protected function relayPurge( $key, $ttl, $holdoff ) {
1140 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1141 // This handles the mcrouter and the single-DC case
1142 $ok = $this->cache->set( $key,
1143 $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
1144 $ttl
1145 );
1146 } else {
1147 $event = $this->cache->modifySimpleRelayEvent( [
1148 'cmd' => 'set',
1149 'key' => $key,
1150 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1151 'ttl' => max( $ttl, 1 ),
1152 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1153 ] );
1154
1155 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1156 if ( !$ok ) {
1157 $this->lastRelayError = self::ERR_RELAY;
1158 }
1159 }
1160
1161 return $ok;
1162 }
1163
1164 /**
1165 * Do the actual async bus delete of a key
1166 *
1167 * @param string $key Cache key
1168 * @return bool Success
1169 */
1170 protected function relayDelete( $key ) {
1171 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1172 // This handles the mcrouter and the single-DC case
1173 $ok = $this->cache->delete( $key );
1174 } else {
1175 $event = $this->cache->modifySimpleRelayEvent( [
1176 'cmd' => 'delete',
1177 'key' => $key,
1178 ] );
1179
1180 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1181 if ( !$ok ) {
1182 $this->lastRelayError = self::ERR_RELAY;
1183 }
1184 }
1185
1186 return $ok;
1187 }
1188
1189 /**
1190 * Check if a key should be regenerated (using random probability)
1191 *
1192 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
1193 * of returning true increases steadily from 0% to 100% as the $curTTL
1194 * moves from $lowTTL to 0 seconds. This handles widely varying
1195 * levels of cache access traffic.
1196 *
1197 * @param float $curTTL Approximate TTL left on the key if present
1198 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1199 * @return bool
1200 */
1201 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1202 if ( $curTTL >= $lowTTL ) {
1203 return false;
1204 } elseif ( $curTTL <= 0 ) {
1205 return true;
1206 }
1207
1208 $chance = ( 1 - $curTTL / $lowTTL );
1209
1210 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1211 }
1212
1213 /**
1214 * Check if a key is due for randomized regeneration due to its popularity
1215 *
1216 * This is used so that popular keys can preemptively refresh themselves for higher
1217 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
1218 * in cache with their high nominal TTL. This means popular keys keep good consistency,
1219 * whether the data changes frequently or not, and long-tail keys get to stay in cache
1220 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
1221 *
1222 * @param float $asOf UNIX timestamp of the value
1223 * @param integer $ageNew Age of key when this might recommend refreshing (seconds)
1224 * @param integer $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
1225 * @return bool
1226 */
1227 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh ) {
1228 $age = microtime( true ) - $asOf;
1229 $timeOld = $age - $ageNew;
1230 if ( $timeOld <= 0 ) {
1231 return false;
1232 }
1233
1234 // Lifecycle is: new, ramp-up refresh chance, full refresh chance
1235 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
1236 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1237 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1238 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1239 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
1240
1241 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1242 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
1243
1244 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1245 }
1246
1247 /**
1248 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1249 *
1250 * @param array $value
1251 * @param bool $versioned
1252 * @param float $asOf The time $value was generated
1253 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1254 * @return bool
1255 */
1256 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1257 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1258 return false;
1259 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1260 return false;
1261 }
1262
1263 return true;
1264 }
1265
1266 /**
1267 * Do not use this method outside WANObjectCache
1268 *
1269 * @param mixed $value
1270 * @param integer $ttl [0=forever]
1271 * @param float $now Unix Current timestamp just before calling set()
1272 * @return array
1273 */
1274 protected function wrap( $value, $ttl, $now ) {
1275 return [
1276 self::FLD_VERSION => self::VERSION,
1277 self::FLD_VALUE => $value,
1278 self::FLD_TTL => $ttl,
1279 self::FLD_TIME => $now
1280 ];
1281 }
1282
1283 /**
1284 * Do not use this method outside WANObjectCache
1285 *
1286 * @param array|string|bool $wrapped
1287 * @param float $now Unix Current timestamp (preferrably pre-query)
1288 * @return array (mixed; false if absent/invalid, current time left)
1289 */
1290 protected function unwrap( $wrapped, $now ) {
1291 // Check if the value is a tombstone
1292 $purge = self::parsePurgeValue( $wrapped );
1293 if ( $purge !== false ) {
1294 // Purged values should always have a negative current $ttl
1295 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1296 return [ false, $curTTL ];
1297 }
1298
1299 if ( !is_array( $wrapped ) // not found
1300 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1301 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1302 ) {
1303 return [ false, null ];
1304 }
1305
1306 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1307 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1308 // Treat as expired, with the cache time as the expiration
1309 $age = $now - $wrapped[self::FLD_TIME];
1310 $curTTL = min( -$age, self::TINY_NEGATIVE );
1311 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1312 // Get the approximate time left on the key
1313 $age = $now - $wrapped[self::FLD_TIME];
1314 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1315 } else {
1316 // Key had no TTL, so the time left is unbounded
1317 $curTTL = INF;
1318 }
1319
1320 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1321 }
1322
1323 /**
1324 * @param array $keys
1325 * @param string $prefix
1326 * @return string[]
1327 */
1328 protected static function prefixCacheKeys( array $keys, $prefix ) {
1329 $res = [];
1330 foreach ( $keys as $key ) {
1331 $res[] = $prefix . $key;
1332 }
1333
1334 return $res;
1335 }
1336
1337 /**
1338 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1339 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1340 * or false if value isn't a valid purge value
1341 */
1342 protected static function parsePurgeValue( $value ) {
1343 if ( !is_string( $value ) ) {
1344 return false;
1345 }
1346 $segments = explode( ':', $value, 3 );
1347 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1348 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1349 ) {
1350 return false;
1351 }
1352 if ( !isset( $segments[2] ) ) {
1353 // Back-compat with old purge values without holdoff
1354 $segments[2] = self::HOLDOFF_TTL;
1355 }
1356 return [
1357 self::FLD_TIME => (float)$segments[1],
1358 self::FLD_HOLDOFF => (int)$segments[2],
1359 ];
1360 }
1361
1362 /**
1363 * @param float $timestamp
1364 * @param int $holdoff In seconds
1365 * @return string Wrapped purge value
1366 */
1367 protected function makePurgeValue( $timestamp, $holdoff ) {
1368 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1369 }
1370
1371 /**
1372 * @param string $group
1373 * @return HashBagOStuff
1374 */
1375 protected function getProcessCache( $group ) {
1376 if ( !isset( $this->processCaches[$group] ) ) {
1377 list( , $n ) = explode( ':', $group );
1378 $this->processCaches[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
1379 }
1380
1381 return $this->processCaches[$group];
1382 }
1383 }