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