Merge "Chinese Conversion Table Update 2016-6"
[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 * @return bool Success
414 */
415 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
416 $now = microtime( true );
417 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
418 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
419 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
420 $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : 0;
421
422 // Do not cache potentially uncommitted data as it might get rolled back
423 if ( !empty( $opts['pending'] ) ) {
424 $this->logger->info( "Rejected set() for $key due to pending writes." );
425
426 return true; // no-op the write for being unsafe
427 }
428
429 $wrapExtra = []; // additional wrapped value fields
430 // Check if there's a risk of writing stale data after the purge tombstone expired
431 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
432 // Case A: read lag with "lockTSE"; save but record value as stale
433 if ( $lockTSE >= 0 ) {
434 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
435 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
436 // Case B: any long-running transaction; ignore this set()
437 } elseif ( $age > self::MAX_READ_LAG ) {
438 $this->logger->warning( "Rejected set() for $key due to snapshot lag." );
439
440 return true; // no-op the write for being unsafe
441 // Case C: high replication lag; lower TTL instead of ignoring all set()s
442 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
443 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
444 $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
445 // Case D: medium length request with medium replication lag; ignore this set()
446 } else {
447 $this->logger->warning( "Rejected set() for $key due to high read lag." );
448
449 return true; // no-op the write for being unsafe
450 }
451 }
452
453 // Wrap that value with time/TTL/version metadata
454 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
455
456 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
457 return ( is_string( $cWrapped ) )
458 ? false // key is tombstoned; do nothing
459 : $wrapped;
460 };
461
462 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl + $staleTTL, 1 );
463 }
464
465 /**
466 * Purge a key from all datacenters
467 *
468 * This should only be called when the underlying data (being cached)
469 * changes in a significant way. This deletes the key and starts a hold-off
470 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
471 * This is done to avoid the following race condition:
472 * - a) Some DB data changes and delete() is called on a corresponding key
473 * - b) A request refills the key with a stale value from a lagged DB
474 * - c) The stale value is stuck there until the key is expired/evicted
475 *
476 * This is implemented by storing a special "tombstone" value at the cache
477 * key that this class recognizes; get() calls will return false for the key
478 * and any set() calls will refuse to replace tombstone values at the key.
479 * For this to always avoid stale value writes, the following must hold:
480 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
481 * - b) If lag is higher, the DB will have gone into read-only mode already
482 *
483 * Note that set() can also be lag-aware and lower the TTL if it's high.
484 *
485 * When using potentially long-running ACID transactions, a good pattern is
486 * to use a pre-commit hook to issue the delete. This means that immediately
487 * after commit, callers will see the tombstone in cache upon purge relay.
488 * It also avoids the following race condition:
489 * - a) T1 begins, changes a row, and calls delete()
490 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
491 * - c) T2 starts, reads the row and calls set() due to a cache miss
492 * - d) T1 finally commits
493 * - e) Stale value is stuck in cache
494 *
495 * Example usage:
496 * @code
497 * $dbw->startAtomic( __METHOD__ ); // start of request
498 * ... <execute some stuff> ...
499 * // Update the row in the DB
500 * $dbw->update( ... );
501 * $key = $cache->makeKey( 'homes', $homeId );
502 * // Purge the corresponding cache entry just before committing
503 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
504 * $cache->delete( $key );
505 * } );
506 * ... <execute some stuff> ...
507 * $dbw->endAtomic( __METHOD__ ); // end of request
508 * @endcode
509 *
510 * The $ttl parameter can be used when purging values that have not actually changed
511 * recently. For example, a cleanup script to purge cache entries does not really need
512 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
513 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
514 *
515 * If called twice on the same key, then the last hold-off TTL takes precedence. For
516 * idempotence, the $ttl should not vary for different delete() calls on the same key.
517 *
518 * @param string $key Cache key
519 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
520 * @return bool True if the item was purged or not found, false on failure
521 */
522 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
523 $key = self::VALUE_KEY_PREFIX . $key;
524
525 if ( $ttl <= 0 ) {
526 // Publish the purge to all datacenters
527 $ok = $this->relayDelete( $key );
528 } else {
529 // Publish the purge to all datacenters
530 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE );
531 }
532
533 return $ok;
534 }
535
536 /**
537 * Fetch the value of a timestamp "check" key
538 *
539 * The key will be *initialized* to the current time if not set,
540 * so only call this method if this behavior is actually desired
541 *
542 * The timestamp can be used to check whether a cached value is valid.
543 * Callers should not assume that this returns the same timestamp in
544 * all datacenters due to relay delays.
545 *
546 * The level of staleness can roughly be estimated from this key, but
547 * if the key was evicted from cache, such calculations may show the
548 * time since expiry as ~0 seconds.
549 *
550 * Note that "check" keys won't collide with other regular keys.
551 *
552 * @param string $key
553 * @return float UNIX timestamp of the check key
554 */
555 final public function getCheckKeyTime( $key ) {
556 $key = self::TIME_KEY_PREFIX . $key;
557
558 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
559 if ( $purge !== false ) {
560 $time = $purge[self::FLD_TIME];
561 } else {
562 // Casting assures identical floats for the next getCheckKeyTime() calls
563 $now = (string)microtime( true );
564 $this->cache->add( $key,
565 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
566 self::CHECK_KEY_TTL
567 );
568 $time = (float)$now;
569 }
570
571 return $time;
572 }
573
574 /**
575 * Purge a "check" key from all datacenters, invalidating keys that use it
576 *
577 * This should only be called when the underlying data (being cached)
578 * changes in a significant way, and it is impractical to call delete()
579 * on all keys that should be changed. When get() is called on those
580 * keys, the relevant "check" keys must be supplied for this to work.
581 *
582 * The "check" key essentially represents a last-modified field.
583 * When touched, the field will be updated on all cache servers.
584 * Keys using it via get(), getMulti(), or getWithSetCallback() will
585 * be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
586 * by those methods to avoid race conditions where dependent keys get updated
587 * with stale values (e.g. from a DB replica DB).
588 *
589 * This is typically useful for keys with hardcoded names or in some cases
590 * dynamically generated names where a low number of combinations exist.
591 * When a few important keys get a large number of hits, a high cache
592 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
593 * method is less appropriate in such cases since the "time since expiry"
594 * cannot be inferred, causing any get() after the reset to treat the key
595 * as being "hot", resulting in more stale value usage.
596 *
597 * Note that "check" keys won't collide with other regular keys.
598 *
599 * @see WANObjectCache::get()
600 * @see WANObjectCache::getWithSetCallback()
601 * @see WANObjectCache::resetCheckKey()
602 *
603 * @param string $key Cache key
604 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
605 * @return bool True if the item was purged or not found, false on failure
606 */
607 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
608 // Publish the purge to all datacenters
609 return $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
610 }
611
612 /**
613 * Delete a "check" key from all datacenters, invalidating keys that use it
614 *
615 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
616 * or getWithSetCallback() will be invalidated. The differences are:
617 * - a) The "check" key will be deleted from all caches and lazily
618 * re-initialized when accessed (rather than set everywhere)
619 * - b) Thus, dependent keys will be known to be invalid, but not
620 * for how long (they are treated as "just" purged), which
621 * effects any lockTSE logic in getWithSetCallback()
622 * - c) Since "check" keys are initialized only on the server the key hashes
623 * to, any temporary ejection of that server will cause the value to be
624 * seen as purged as a new server will initialize the "check" key.
625 *
626 * The advantage is that this does not place high TTL keys on every cache
627 * server, making it better for code that will cache many different keys
628 * and either does not use lockTSE or uses a low enough TTL anyway.
629 *
630 * This is typically useful for keys with dynamically generated names
631 * where a high number of combinations exist.
632 *
633 * Note that "check" keys won't collide with other regular keys.
634 *
635 * @see WANObjectCache::get()
636 * @see WANObjectCache::getWithSetCallback()
637 * @see WANObjectCache::touchCheckKey()
638 *
639 * @param string $key Cache key
640 * @return bool True if the item was purged or not found, false on failure
641 */
642 final public function resetCheckKey( $key ) {
643 // Publish the purge to all datacenters
644 return $this->relayDelete( self::TIME_KEY_PREFIX . $key );
645 }
646
647 /**
648 * Method to fetch/regenerate cache keys
649 *
650 * On cache miss, the key will be set to the callback result via set()
651 * (unless the callback returns false) and that result will be returned.
652 * The arguments supplied to the callback are:
653 * - $oldValue : current cache value or false if not present
654 * - &$ttl : a reference to the TTL which can be altered
655 * - &$setOpts : a reference to options for set() which can be altered
656 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
657 *
658 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
659 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
660 * value, but it can be used to maintain "most recent X" values that come from time or
661 * sequence based source data, provided that the "as of" id/time is tracked. Note that
662 * preemptive regeneration and $checkKeys can result in a non-false current value.
663 *
664 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
665 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
666 * regeneration will automatically be triggered using the callback.
667 *
668 * The simplest way to avoid stampedes for hot keys is to use
669 * the 'lockTSE' option in $opts. If cache purges are needed, also:
670 * - a) Pass $key into $checkKeys
671 * - b) Use touchCheckKey( $key ) instead of delete( $key )
672 *
673 * Example usage (typical key):
674 * @code
675 * $catInfo = $cache->getWithSetCallback(
676 * // Key to store the cached value under
677 * $cache->makeKey( 'cat-attributes', $catId ),
678 * // Time-to-live (in seconds)
679 * $cache::TTL_MINUTE,
680 * // Function that derives the new key value
681 * function ( $oldValue, &$ttl, array &$setOpts ) {
682 * $dbr = wfGetDB( DB_REPLICA );
683 * // Account for any snapshot/replica DB lag
684 * $setOpts += Database::getCacheSetOptions( $dbr );
685 *
686 * return $dbr->selectRow( ... );
687 * }
688 * );
689 * @endcode
690 *
691 * Example usage (key that is expensive and hot):
692 * @code
693 * $catConfig = $cache->getWithSetCallback(
694 * // Key to store the cached value under
695 * $cache->makeKey( 'site-cat-config' ),
696 * // Time-to-live (in seconds)
697 * $cache::TTL_DAY,
698 * // Function that derives the new key value
699 * function ( $oldValue, &$ttl, array &$setOpts ) {
700 * $dbr = wfGetDB( DB_REPLICA );
701 * // Account for any snapshot/replica DB lag
702 * $setOpts += Database::getCacheSetOptions( $dbr );
703 *
704 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
705 * },
706 * [
707 * // Calling touchCheckKey() on this key invalidates the cache
708 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
709 * // Try to only let one datacenter thread manage cache updates at a time
710 * 'lockTSE' => 30,
711 * // Avoid querying cache servers multiple times in a web request
712 * 'pcTTL' => $cache::TTL_PROC_LONG
713 * ]
714 * );
715 * @endcode
716 *
717 * Example usage (key with dynamic dependencies):
718 * @code
719 * $catState = $cache->getWithSetCallback(
720 * // Key to store the cached value under
721 * $cache->makeKey( 'cat-state', $cat->getId() ),
722 * // Time-to-live (seconds)
723 * $cache::TTL_HOUR,
724 * // Function that derives the new key value
725 * function ( $oldValue, &$ttl, array &$setOpts ) {
726 * // Determine new value from the DB
727 * $dbr = wfGetDB( DB_REPLICA );
728 * // Account for any snapshot/replica DB lag
729 * $setOpts += Database::getCacheSetOptions( $dbr );
730 *
731 * return CatState::newFromResults( $dbr->select( ... ) );
732 * },
733 * [
734 * // The "check" keys that represent things the value depends on;
735 * // Calling touchCheckKey() on any of them invalidates the cache
736 * 'checkKeys' => [
737 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
738 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
739 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
740 * ]
741 * ]
742 * );
743 * @endcode
744 *
745 * Example usage (hot key holding most recent 100 events):
746 * @code
747 * $lastCatActions = $cache->getWithSetCallback(
748 * // Key to store the cached value under
749 * $cache->makeKey( 'cat-last-actions', 100 ),
750 * // Time-to-live (in seconds)
751 * 10,
752 * // Function that derives the new key value
753 * function ( $oldValue, &$ttl, array &$setOpts ) {
754 * $dbr = wfGetDB( DB_REPLICA );
755 * // Account for any snapshot/replica DB lag
756 * $setOpts += Database::getCacheSetOptions( $dbr );
757 *
758 * // Start off with the last cached list
759 * $list = $oldValue ?: [];
760 * // Fetch the last 100 relevant rows in descending order;
761 * // only fetch rows newer than $list[0] to reduce scanning
762 * $rows = iterator_to_array( $dbr->select( ... ) );
763 * // Merge them and get the new "last 100" rows
764 * return array_slice( array_merge( $new, $list ), 0, 100 );
765 * },
766 * [
767 * // Try to only let one datacenter thread manage cache updates at a time
768 * 'lockTSE' => 30,
769 * // Use a magic value when no cache value is ready rather than stampeding
770 * 'busyValue' => 'computing'
771 * ]
772 * );
773 * @endcode
774 *
775 * @see WANObjectCache::get()
776 * @see WANObjectCache::set()
777 *
778 * @param string $key Cache key
779 * @param integer $ttl Seconds to live for key updates. Special values are:
780 * - WANObjectCache::TTL_INDEFINITE: Cache forever
781 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
782 * @param callable $callback Value generation function
783 * @param array $opts Options map:
784 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
785 * touchCheckKey() or resetCheckKey() is called on any of these keys.
786 * Default: [].
787 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
788 * ago, then try to have a single thread handle cache regeneration at any given time.
789 * Other threads will try to use stale values if possible. If, on miss, the time since
790 * expiration is low, the assumption is that the key is hot and that a stampede is worth
791 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
792 * higher this is set, the higher the worst-case staleness can be.
793 * Use WANObjectCache::TSE_NONE to disable this logic.
794 * Default: WANObjectCache::TSE_NONE.
795 * - busyValue: If no value exists and another thread is currently regenerating it, use this
796 * as a fallback value (or a callback to generate such a value). This assures that cache
797 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
798 * against cache regeneration becoming very slow for some reason (greater than the TTL).
799 * Default: null.
800 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
801 * network I/O when a key is read several times. This will not cache when the callback
802 * returns false, however. Note that any purges will not be seen while process cached;
803 * since the callback should use replica DBs and they may be lagged or have snapshot
804 * isolation anyway, this should not typically matter.
805 * Default: WANObjectCache::TTL_UNCACHEABLE.
806 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
807 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
808 * large values, small yet numerous values, or some values with a high cost of eviction.
809 * It is generally preferable to use a class constant when setting this value.
810 * This has no effect unless pcTTL is used.
811 * Default: WANObjectCache::PC_PRIMARY.
812 * - version: Integer version number. This allows for callers to make breaking changes to
813 * how values are stored while maintaining compatability and correct cache purges. New
814 * versions are stored alongside older versions concurrently. Avoid storing class objects
815 * however, as this reduces compatibility (due to serialization).
816 * Default: null.
817 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
818 * This is useful if the source of a key is suspected of having possibly changed
819 * recently, and the caller wants any such changes to be reflected.
820 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
821 * - hotTTR: Expected time-till-refresh for keys that average ~1 hit/second.
822 * This should be greater than "ageNew". Keys with higher hit rates will regenerate
823 * more often. This is useful when a popular key is changed but the cache purge was
824 * delayed or lost. Seldom used keys are rarely affected by this setting, unless an
825 * extremely low "hotTTR" value is passed in.
826 * Default: WANObjectCache::HOT_TTR.
827 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
828 * than this. It becomes more likely over time, becoming certain once the key is expired.
829 * Default: WANObjectCache::LOW_TTL.
830 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
831 * Default: WANObjectCache::AGE_NEW.
832 * @return mixed Value found or written to the key
833 * @note Callable type hints are not used to avoid class-autoloading
834 */
835 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
836 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
837
838 // Try the process cache if enabled
839 if ( $pcTTL >= 0 ) {
840 $group = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY;
841 $procCache = $this->getProcessCache( $group );
842 $value = $procCache->get( $key );
843 } else {
844 $procCache = false;
845 $value = false;
846 }
847
848 if ( $value === false ) {
849 // Fetch the value over the network
850 if ( isset( $opts['version'] ) ) {
851 $version = $opts['version'];
852 $asOf = null;
853 $cur = $this->doGetWithSetCallback(
854 $key,
855 $ttl,
856 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
857 use ( $callback, $version ) {
858 if ( is_array( $oldValue )
859 && array_key_exists( self::VFLD_DATA, $oldValue )
860 ) {
861 $oldData = $oldValue[self::VFLD_DATA];
862 } else {
863 // VFLD_DATA is not set if an old, unversioned, key is present
864 $oldData = false;
865 }
866
867 return [
868 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
869 self::VFLD_VERSION => $version
870 ];
871 },
872 $opts,
873 $asOf
874 );
875 if ( $cur[self::VFLD_VERSION] === $version ) {
876 // Value created or existed before with version; use it
877 $value = $cur[self::VFLD_DATA];
878 } else {
879 // Value existed before with a different version; use variant key.
880 // Reflect purges to $key by requiring that this key value be newer.
881 $value = $this->doGetWithSetCallback(
882 'cache-variant:' . md5( $key ) . ":$version",
883 $ttl,
884 $callback,
885 // Regenerate value if not newer than $key
886 [ 'version' => null, 'minAsOf' => $asOf ] + $opts
887 );
888 }
889 } else {
890 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
891 }
892
893 // Update the process cache if enabled
894 if ( $procCache && $value !== false ) {
895 $procCache->set( $key, $value, $pcTTL );
896 }
897 }
898
899 return $value;
900 }
901
902 /**
903 * Do the actual I/O for getWithSetCallback() when needed
904 *
905 * @see WANObjectCache::getWithSetCallback()
906 *
907 * @param string $key
908 * @param integer $ttl
909 * @param callback $callback
910 * @param array $opts Options map for getWithSetCallback()
911 * @param float &$asOf Cache generation timestamp of returned value [returned]
912 * @return mixed
913 * @note Callable type hints are not used to avoid class-autoloading
914 */
915 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
916 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
917 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
918 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
919 $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
920 $popWindow = isset( $opts['hotTTR'] ) ? $opts['hotTTR'] : self::HOT_TTR;
921 $ageNew = isset( $opts['ageNew'] ) ? $opts['ageNew'] : self::AGE_NEW;
922 $minTime = isset( $opts['minAsOf'] ) ? $opts['minAsOf'] : self::MIN_TIMESTAMP_NONE;
923 $versioned = isset( $opts['version'] );
924
925 // Get the current key value
926 $curTTL = null;
927 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
928 $value = $cValue; // return value
929
930 // Determine if a regeneration is desired
931 if ( $value !== false
932 && $curTTL > 0
933 && $this->isValid( $value, $versioned, $asOf, $minTime )
934 && !$this->worthRefreshExpiring( $curTTL, $lowTTL )
935 && !$this->worthRefreshPopular( $asOf, $ageNew, $popWindow )
936 ) {
937 return $value;
938 }
939
940 // A deleted key with a negative TTL left must be tombstoned
941 $isTombstone = ( $curTTL !== null && $value === false );
942 // Assume a key is hot if requested soon after invalidation
943 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
944 // Use the mutex if there is no value and a busy fallback is given
945 $checkBusy = ( $busyValue !== null && $value === false );
946 // Decide whether a single thread should handle regenerations.
947 // This avoids stampedes when $checkKeys are bumped and when preemptive
948 // renegerations take too long. It also reduces regenerations while $key
949 // is tombstoned. This balances cache freshness with avoiding DB load.
950 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
951
952 $lockAcquired = false;
953 if ( $useMutex ) {
954 // Acquire a datacenter-local non-blocking lock
955 if ( $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
956 // Lock acquired; this thread should update the key
957 $lockAcquired = true;
958 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
959 // If it cannot be acquired; then the stale value can be used
960 return $value;
961 } else {
962 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
963 // For hot keys, either another thread has the lock or the lock failed;
964 // use the INTERIM value from the last thread that regenerated it.
965 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
966 list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
967 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
968 $asOf = $wrapped[self::FLD_TIME];
969
970 return $value;
971 }
972 // Use the busy fallback value if nothing else
973 if ( $busyValue !== null ) {
974 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
975 }
976 }
977 }
978
979 if ( !is_callable( $callback ) ) {
980 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
981 }
982
983 // Generate the new value from the callback...
984 $setOpts = [];
985 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
986 // When delete() is called, writes are write-holed by the tombstone,
987 // so use a special INTERIM key to pass the new value around threads.
988 if ( ( $isTombstone && $lockTSE > 0 ) && $value !== false && $ttl >= 0 ) {
989 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
990 $newAsOf = microtime( true );
991 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
992 // Avoid using set() to avoid pointless mcrouter broadcasting
993 $this->cache->merge(
994 self::INTERIM_KEY_PREFIX . $key,
995 function () use ( $wrapped ) {
996 return $wrapped;
997 },
998 $tempTTL,
999 1
1000 );
1001 }
1002
1003 if ( $value !== false && $ttl >= 0 ) {
1004 // Update the cache; this will fail if the key is tombstoned
1005 $setOpts['lockTSE'] = $lockTSE;
1006 $this->set( $key, $value, $ttl, $setOpts );
1007 }
1008
1009 if ( $lockAcquired ) {
1010 // Avoid using delete() to avoid pointless mcrouter broadcasting
1011 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, 1 );
1012 }
1013
1014 return $value;
1015 }
1016
1017 /**
1018 * @see BagOStuff::makeKey()
1019 * @param string ... Key component
1020 * @return string
1021 * @since 1.27
1022 */
1023 public function makeKey() {
1024 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1025 }
1026
1027 /**
1028 * @see BagOStuff::makeGlobalKey()
1029 * @param string ... Key component
1030 * @return string
1031 * @since 1.27
1032 */
1033 public function makeGlobalKey() {
1034 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1035 }
1036
1037 /**
1038 * Get the "last error" registered; clearLastError() should be called manually
1039 * @return int ERR_* class constant for the "last error" registry
1040 */
1041 final public function getLastError() {
1042 if ( $this->lastRelayError ) {
1043 // If the cache and the relayer failed, focus on the latter.
1044 // An update not making it to the relayer means it won't show up
1045 // in other DCs (nor will consistent re-hashing see up-to-date values).
1046 // On the other hand, if just the cache update failed, then it should
1047 // eventually be applied by the relayer.
1048 return $this->lastRelayError;
1049 }
1050
1051 $code = $this->cache->getLastError();
1052 switch ( $code ) {
1053 case BagOStuff::ERR_NONE:
1054 return self::ERR_NONE;
1055 case BagOStuff::ERR_NO_RESPONSE:
1056 return self::ERR_NO_RESPONSE;
1057 case BagOStuff::ERR_UNREACHABLE:
1058 return self::ERR_UNREACHABLE;
1059 default:
1060 return self::ERR_UNEXPECTED;
1061 }
1062 }
1063
1064 /**
1065 * Clear the "last error" registry
1066 */
1067 final public function clearLastError() {
1068 $this->cache->clearLastError();
1069 $this->lastRelayError = self::ERR_NONE;
1070 }
1071
1072 /**
1073 * Clear the in-process caches; useful for testing
1074 *
1075 * @since 1.27
1076 */
1077 public function clearProcessCache() {
1078 $this->processCaches = [];
1079 }
1080
1081 /**
1082 * @param integer $flag ATTR_* class constant
1083 * @return integer QOS_* class constant
1084 * @since 1.28
1085 */
1086 public function getQoS( $flag ) {
1087 return $this->cache->getQoS( $flag );
1088 }
1089
1090 /**
1091 * Get a TTL that is higher for objects that have not changed recently
1092 *
1093 * This is useful for keys that get explicit purges and DB or purge relay
1094 * lag is a potential concern (especially how it interacts with CDN cache)
1095 *
1096 * Example usage:
1097 * @code
1098 * // Last-modified time of page
1099 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1100 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1101 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1102 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1103 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1104 * @endcode
1105 *
1106 * @param integer|float $mtime UNIX timestamp
1107 * @param integer $maxTTL Maximum TTL (seconds)
1108 * @param integer $minTTL Minimum TTL (seconds); Default: 30
1109 * @param float $factor Value in the range (0,1); Default: .2
1110 * @return integer Adaptive TTL
1111 * @since 1.28
1112 */
1113 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = .2 ) {
1114 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
1115 $mtime = (int)$mtime; // handle fractional seconds and string integers
1116 }
1117
1118 if ( !is_int( $mtime ) || $mtime <= 0 ) {
1119 return $minTTL; // no last-modified time provided
1120 }
1121
1122 $age = time() - $mtime;
1123
1124 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1125 }
1126
1127 /**
1128 * Do the actual async bus purge of a key
1129 *
1130 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1131 *
1132 * @param string $key Cache key
1133 * @param integer $ttl How long to keep the tombstone [seconds]
1134 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1135 * @return bool Success
1136 */
1137 protected function relayPurge( $key, $ttl, $holdoff ) {
1138 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1139 // This handles the mcrouter and the single-DC case
1140 $ok = $this->cache->set( $key,
1141 $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
1142 $ttl
1143 );
1144 } else {
1145 $event = $this->cache->modifySimpleRelayEvent( [
1146 'cmd' => 'set',
1147 'key' => $key,
1148 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1149 'ttl' => max( $ttl, 1 ),
1150 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1151 ] );
1152
1153 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1154 if ( !$ok ) {
1155 $this->lastRelayError = self::ERR_RELAY;
1156 }
1157 }
1158
1159 return $ok;
1160 }
1161
1162 /**
1163 * Do the actual async bus delete of a key
1164 *
1165 * @param string $key Cache key
1166 * @return bool Success
1167 */
1168 protected function relayDelete( $key ) {
1169 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1170 // This handles the mcrouter and the single-DC case
1171 $ok = $this->cache->delete( $key );
1172 } else {
1173 $event = $this->cache->modifySimpleRelayEvent( [
1174 'cmd' => 'delete',
1175 'key' => $key,
1176 ] );
1177
1178 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1179 if ( !$ok ) {
1180 $this->lastRelayError = self::ERR_RELAY;
1181 }
1182 }
1183
1184 return $ok;
1185 }
1186
1187 /**
1188 * Check if a key should be regenerated (using random probability)
1189 *
1190 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
1191 * of returning true increases steadily from 0% to 100% as the $curTTL
1192 * moves from $lowTTL to 0 seconds. This handles widely varying
1193 * levels of cache access traffic.
1194 *
1195 * @param float $curTTL Approximate TTL left on the key if present
1196 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1197 * @return bool
1198 */
1199 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1200 if ( $curTTL >= $lowTTL ) {
1201 return false;
1202 } elseif ( $curTTL <= 0 ) {
1203 return true;
1204 }
1205
1206 $chance = ( 1 - $curTTL / $lowTTL );
1207
1208 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1209 }
1210
1211 /**
1212 * Check if a key is due for randomized regeneration due to its popularity
1213 *
1214 * This is used so that popular keys can preemptively refresh themselves for higher
1215 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
1216 * in cache with their high nominal TTL. This means popular keys keep good consistency,
1217 * whether the data changes frequently or not, and long-tail keys get to stay in cache
1218 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
1219 *
1220 * @param float $asOf UNIX timestamp of the value
1221 * @param integer $ageNew Age of key when this might recommend refreshing (seconds)
1222 * @param integer $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
1223 * @return bool
1224 */
1225 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh ) {
1226 $age = microtime( true ) - $asOf;
1227 $timeOld = $age - $ageNew;
1228 if ( $timeOld <= 0 ) {
1229 return false;
1230 }
1231
1232 // Lifecycle is: new, ramp-up refresh chance, full refresh chance
1233 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
1234 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1235 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1236 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1237 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
1238
1239 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1240 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
1241
1242 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1243 }
1244
1245 /**
1246 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1247 *
1248 * @param array $value
1249 * @param bool $versioned
1250 * @param float $asOf The time $value was generated
1251 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1252 * @return bool
1253 */
1254 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1255 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1256 return false;
1257 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1258 return false;
1259 }
1260
1261 return true;
1262 }
1263
1264 /**
1265 * Do not use this method outside WANObjectCache
1266 *
1267 * @param mixed $value
1268 * @param integer $ttl [0=forever]
1269 * @param float $now Unix Current timestamp just before calling set()
1270 * @return array
1271 */
1272 protected function wrap( $value, $ttl, $now ) {
1273 return [
1274 self::FLD_VERSION => self::VERSION,
1275 self::FLD_VALUE => $value,
1276 self::FLD_TTL => $ttl,
1277 self::FLD_TIME => $now
1278 ];
1279 }
1280
1281 /**
1282 * Do not use this method outside WANObjectCache
1283 *
1284 * @param array|string|bool $wrapped
1285 * @param float $now Unix Current timestamp (preferrably pre-query)
1286 * @return array (mixed; false if absent/invalid, current time left)
1287 */
1288 protected function unwrap( $wrapped, $now ) {
1289 // Check if the value is a tombstone
1290 $purge = self::parsePurgeValue( $wrapped );
1291 if ( $purge !== false ) {
1292 // Purged values should always have a negative current $ttl
1293 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1294 return [ false, $curTTL ];
1295 }
1296
1297 if ( !is_array( $wrapped ) // not found
1298 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1299 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1300 ) {
1301 return [ false, null ];
1302 }
1303
1304 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1305 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1306 // Treat as expired, with the cache time as the expiration
1307 $age = $now - $wrapped[self::FLD_TIME];
1308 $curTTL = min( -$age, self::TINY_NEGATIVE );
1309 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1310 // Get the approximate time left on the key
1311 $age = $now - $wrapped[self::FLD_TIME];
1312 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1313 } else {
1314 // Key had no TTL, so the time left is unbounded
1315 $curTTL = INF;
1316 }
1317
1318 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1319 }
1320
1321 /**
1322 * @param array $keys
1323 * @param string $prefix
1324 * @return string[]
1325 */
1326 protected static function prefixCacheKeys( array $keys, $prefix ) {
1327 $res = [];
1328 foreach ( $keys as $key ) {
1329 $res[] = $prefix . $key;
1330 }
1331
1332 return $res;
1333 }
1334
1335 /**
1336 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1337 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1338 * or false if value isn't a valid purge value
1339 */
1340 protected static function parsePurgeValue( $value ) {
1341 if ( !is_string( $value ) ) {
1342 return false;
1343 }
1344 $segments = explode( ':', $value, 3 );
1345 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1346 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1347 ) {
1348 return false;
1349 }
1350 if ( !isset( $segments[2] ) ) {
1351 // Back-compat with old purge values without holdoff
1352 $segments[2] = self::HOLDOFF_TTL;
1353 }
1354 return [
1355 self::FLD_TIME => (float)$segments[1],
1356 self::FLD_HOLDOFF => (int)$segments[2],
1357 ];
1358 }
1359
1360 /**
1361 * @param float $timestamp
1362 * @param int $holdoff In seconds
1363 * @return string Wrapped purge value
1364 */
1365 protected function makePurgeValue( $timestamp, $holdoff ) {
1366 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1367 }
1368
1369 /**
1370 * @param string $group
1371 * @return HashBagOStuff
1372 */
1373 protected function getProcessCache( $group ) {
1374 if ( !isset( $this->processCaches[$group] ) ) {
1375 list( , $n ) = explode( ':', $group );
1376 $this->processCaches[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
1377 }
1378
1379 return $this->processCaches[$group];
1380 }
1381 }