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