objectcache: fix some makeKey/makeGlobalKey IDEA warnings
[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 */
21
22 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
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 three 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 * - c) Ignore the 'purge' EventRelayer configuration (default is NullEventRelayer)
57 * and set up dynomite as cache middleware between the web servers and either
58 * memcached or redis. This will also broadcast all key setting operations, not just purges,
59 * which can be useful for cache warming. Writes are eventually consistent via the
60 * Dynamo replication model (see https://github.com/Netflix/dynomite).
61 *
62 * Broadcasted operations like delete() and touchCheckKey() are done asynchronously
63 * in all datacenters this way, though the local one should likely be near immediate.
64 *
65 * This means that callers in all datacenters may see older values for however many
66 * milliseconds that the purge took to reach that datacenter. As with any cache, this
67 * should not be relied on for cases where reads are used to determine writes to source
68 * (e.g. non-cache) data stores, except when reading immutable data.
69 *
70 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
71 * to avoid collisions with keys that are not wrapped as metadata arrays. The
72 * prefixes are as follows:
73 * - a) "WANCache:v" : used for regular value keys
74 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
75 * - c) "WANCache:t" : used for storing timestamp "check" keys
76 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
77 *
78 * @ingroup Cache
79 * @since 1.26
80 */
81 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
82 /** @var BagOStuff The local datacenter cache */
83 protected $cache;
84 /** @var HashBagOStuff[] Map of group PHP instance caches */
85 protected $processCaches = [];
86 /** @var string Purge channel name */
87 protected $purgeChannel;
88 /** @var EventRelayer Bus that handles purge broadcasts */
89 protected $purgeRelayer;
90 /** @var LoggerInterface */
91 protected $logger;
92 /** @var StatsdDataFactoryInterface */
93 protected $stats;
94
95 /** @var int ERR_* constant for the "last error" registry */
96 protected $lastRelayError = self::ERR_NONE;
97
98 /** @var int Callback stack depth for getWithSetCallback() */
99 private $callbackDepth = 0;
100 /** @var mixed[] Temporary warm-up cache */
101 private $warmupCache = [];
102 /** @var int Key fetched */
103 private $warmupKeyMisses = 0;
104
105 /** Max time expected to pass between delete() and DB commit finishing */
106 const MAX_COMMIT_DELAY = 3;
107 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
108 const MAX_READ_LAG = 7;
109 /** Seconds to tombstone keys on delete() */
110 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
111
112 /** Seconds to keep dependency purge keys around */
113 const CHECK_KEY_TTL = self::TTL_YEAR;
114 /** Seconds to keep lock keys around */
115 const LOCK_TTL = 10;
116 /** Default remaining TTL at which to consider pre-emptive regeneration */
117 const LOW_TTL = 30;
118 /** Default time-since-expiry on a miss that makes a key "hot" */
119 const LOCK_TSE = 1;
120
121 /** Never consider performing "popularity" refreshes until a key reaches this age */
122 const AGE_NEW = 60;
123 /** The time length of the "popularity" refresh window for hot keys */
124 const HOT_TTR = 900;
125 /** Hits/second for a refresh to be expected within the "popularity" window */
126 const HIT_RATE_HIGH = 1;
127 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
128 const RAMPUP_TTL = 30;
129
130 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
131 const TTL_UNCACHEABLE = -1;
132 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
133 const TSE_NONE = -1;
134 /** Max TTL to store keys when a data sourced is lagged */
135 const TTL_LAGGED = 30;
136 /** Idiom for delete() for "no hold-off" */
137 const HOLDOFF_NONE = 0;
138 /** Idiom for getWithSetCallback() for "no minimum required as-of timestamp" */
139 const MIN_TIMESTAMP_NONE = 0.0;
140
141 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
142 const TINY_NEGATIVE = -0.000001;
143
144 /** Cache format version number */
145 const VERSION = 1;
146
147 const FLD_VERSION = 0; // key to cache version number
148 const FLD_VALUE = 1; // key to the cached value
149 const FLD_TTL = 2; // key to the original TTL
150 const FLD_TIME = 3; // key to the cache time
151 const FLD_FLAGS = 4; // key to the flags bitfield
152 const FLD_HOLDOFF = 5; // key to any hold-off TTL
153
154 /** @var int Treat this value as expired-on-arrival */
155 const FLG_STALE = 1;
156
157 const ERR_NONE = 0; // no error
158 const ERR_NO_RESPONSE = 1; // no response
159 const ERR_UNREACHABLE = 2; // can't connect
160 const ERR_UNEXPECTED = 3; // response gave some error
161 const ERR_RELAY = 4; // relay broadcast failed
162
163 const VALUE_KEY_PREFIX = 'WANCache:v:';
164 const INTERIM_KEY_PREFIX = 'WANCache:i:';
165 const TIME_KEY_PREFIX = 'WANCache:t:';
166 const MUTEX_KEY_PREFIX = 'WANCache:m:';
167
168 const PURGE_VAL_PREFIX = 'PURGED:';
169
170 const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
171 const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
172
173 const PC_PRIMARY = 'primary:1000'; // process cache name and max key count
174
175 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
176
177 /**
178 * @param array $params
179 * - cache : BagOStuff object for a persistent cache
180 * - channels : Map of (action => channel string). Actions include "purge".
181 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
182 * - logger : LoggerInterface object
183 * - stats : LoggerInterface object
184 */
185 public function __construct( array $params ) {
186 $this->cache = $params['cache'];
187 $this->purgeChannel = isset( $params['channels']['purge'] )
188 ? $params['channels']['purge']
189 : self::DEFAULT_PURGE_CHANNEL;
190 $this->purgeRelayer = isset( $params['relayers']['purge'] )
191 ? $params['relayers']['purge']
192 : new EventRelayerNull( [] );
193 $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
194 $this->stats = isset( $params['stats'] ) ? $params['stats'] : new NullStatsdDataFactory();
195 }
196
197 public function setLogger( LoggerInterface $logger ) {
198 $this->logger = $logger;
199 }
200
201 /**
202 * Get an instance that wraps EmptyBagOStuff
203 *
204 * @return WANObjectCache
205 */
206 public static function newEmpty() {
207 return new self( [
208 'cache' => new EmptyBagOStuff(),
209 'pool' => 'empty'
210 ] );
211 }
212
213 /**
214 * Fetch the value of a key from cache
215 *
216 * If supplied, $curTTL is set to the remaining TTL (current time left):
217 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
218 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
219 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
220 * - d) null; if $key does not exist and is not tombstoned
221 *
222 * If a key is tombstoned, $curTTL will reflect the time since delete().
223 *
224 * The timestamp of $key will be checked against the last-purge timestamp
225 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
226 * initialized to the current timestamp. If any of $checkKeys have a timestamp
227 * greater than that of $key, then $curTTL will reflect how long ago $key
228 * became invalid. Callers can use $curTTL to know when the value is stale.
229 * The $checkKeys parameter allow mass invalidations by updating a single key:
230 * - a) Each "check" key represents "last purged" of some source data
231 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
232 * - c) When the source data that "check" keys represent changes,
233 * the touchCheckKey() method is called on them
234 *
235 * Source data entities might exists in a DB that uses snapshot isolation
236 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
237 * isolation can largely be maintained by doing the following:
238 * - a) Calling delete() on entity change *and* creation, before DB commit
239 * - b) Keeping transaction duration shorter than delete() hold-off TTL
240 *
241 * However, pre-snapshot values might still be seen if an update was made
242 * in a remote datacenter but the purge from delete() didn't relay yet.
243 *
244 * Consider using getWithSetCallback() instead of get() and set() cycles.
245 * That method has cache slam avoiding features for hot/expensive keys.
246 *
247 * @param string $key Cache key made from makeKey() or makeGlobalKey()
248 * @param mixed &$curTTL Approximate TTL left on the key if present/tombstoned [returned]
249 * @param array $checkKeys List of "check" keys
250 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
251 * @return mixed Value of cache key or false on failure
252 */
253 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
254 $curTTLs = [];
255 $asOfs = [];
256 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
257 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
258 $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null;
259
260 return isset( $values[$key] ) ? $values[$key] : false;
261 }
262
263 /**
264 * Fetch the value of several keys from cache
265 *
266 * @see WANObjectCache::get()
267 *
268 * @param array $keys List of cache keys made from makeKey() or makeGlobalKey()
269 * @param array &$curTTLs Map of (key => approximate TTL left) for existing keys [returned]
270 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
271 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
272 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
273 * @return array Map of (key => value) for keys that exist and are not tombstoned
274 */
275 final public function getMulti(
276 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
277 ) {
278 $result = [];
279 $curTTLs = [];
280 $asOfs = [];
281
282 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
283 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
284
285 $checkKeysForAll = [];
286 $checkKeysByKey = [];
287 $checkKeysFlat = [];
288 foreach ( $checkKeys as $i => $checkKeyGroup ) {
289 $prefixed = self::prefixCacheKeys( (array)$checkKeyGroup, self::TIME_KEY_PREFIX );
290 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
291 // Is this check keys for a specific cache key, or for all keys being fetched?
292 if ( is_int( $i ) ) {
293 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
294 } else {
295 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
296 ? array_merge( $checkKeysByKey[$i], $prefixed )
297 : $prefixed;
298 }
299 }
300
301 // Fetch all of the raw values
302 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
303 if ( $this->warmupCache ) {
304 $wrappedValues = array_intersect_key( $this->warmupCache, array_flip( $keysGet ) );
305 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) ); // keys left to fetch
306 $this->warmupKeyMisses += count( $keysGet );
307 } else {
308 $wrappedValues = [];
309 }
310 if ( $keysGet ) {
311 $wrappedValues += $this->cache->getMulti( $keysGet );
312 }
313 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
314 $now = microtime( true );
315
316 // Collect timestamps from all "check" keys
317 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
318 $purgeValuesByKey = [];
319 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
320 $purgeValuesByKey[$cacheKey] =
321 $this->processCheckKeys( $checks, $wrappedValues, $now );
322 }
323
324 // Get the main cache value for each key and validate them
325 foreach ( $valueKeys as $vKey ) {
326 if ( !isset( $wrappedValues[$vKey] ) ) {
327 continue; // not found
328 }
329
330 $key = substr( $vKey, $vPrefixLen ); // unprefix
331
332 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
333 if ( $value !== false ) {
334 $result[$key] = $value;
335
336 // Force dependant keys to be invalid for a while after purging
337 // to reduce race conditions involving stale data getting cached
338 $purgeValues = $purgeValuesForAll;
339 if ( isset( $purgeValuesByKey[$key] ) ) {
340 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
341 }
342 foreach ( $purgeValues as $purge ) {
343 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
344 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
345 // How long ago this value was expired by *this* check key
346 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
347 // How long ago this value was expired by *any* known check key
348 $curTTL = min( $curTTL, $ago );
349 }
350 }
351 }
352 $curTTLs[$key] = $curTTL;
353 $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
354 }
355
356 return $result;
357 }
358
359 /**
360 * @since 1.27
361 * @param array $timeKeys List of prefixed time check keys
362 * @param array $wrappedValues
363 * @param float $now
364 * @return array List of purge value arrays
365 */
366 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
367 $purgeValues = [];
368 foreach ( $timeKeys as $timeKey ) {
369 $purge = isset( $wrappedValues[$timeKey] )
370 ? self::parsePurgeValue( $wrappedValues[$timeKey] )
371 : false;
372 if ( $purge === false ) {
373 // Key is not set or invalid; regenerate
374 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
375 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
376 $purge = self::parsePurgeValue( $newVal );
377 }
378 $purgeValues[] = $purge;
379 }
380 return $purgeValues;
381 }
382
383 /**
384 * Set the value of a key in cache
385 *
386 * Simply calling this method when source data changes is not valid because
387 * the changes do not replicate to the other WAN sites. In that case, delete()
388 * should be used instead. This method is intended for use on cache misses.
389 *
390 * If the data was read from a snapshot-isolated transactions (e.g. the default
391 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
392 * - a) T1 starts
393 * - b) T2 updates a row, calls delete(), and commits
394 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
395 * - d) T1 reads the row and calls set() due to a cache miss
396 * - e) Stale value is stuck in cache
397 *
398 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
399 *
400 * Example usage:
401 * @code
402 * $dbr = wfGetDB( DB_REPLICA );
403 * $setOpts = Database::getCacheSetOptions( $dbr );
404 * // Fetch the row from the DB
405 * $row = $dbr->selectRow( ... );
406 * $key = $cache->makeKey( 'building', $buildingId );
407 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
408 * @endcode
409 *
410 * @param string $key Cache key
411 * @param mixed $value
412 * @param int $ttl Seconds to live. Special values are:
413 * - WANObjectCache::TTL_INDEFINITE: Cache forever
414 * @param array $opts Options map:
415 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
416 * before the data was read or, if applicable, the replica DB lag before
417 * the snapshot-isolated transaction the data was read from started.
418 * Use false to indicate that replication is not running.
419 * Default: 0 seconds
420 * - since : UNIX timestamp of the data in $value. Typically, this is either
421 * the current time the data was read or (if applicable) the time when
422 * the snapshot-isolated transaction the data was read from started.
423 * Default: 0 seconds
424 * - pending : Whether this data is possibly from an uncommitted write transaction.
425 * Generally, other threads should not see values from the future and
426 * they certainly should not see ones that ended up getting rolled back.
427 * Default: false
428 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
429 * with this TTL and flag it as stale. This is only useful if the reads for
430 * this key use getWithSetCallback() with "lockTSE" set.
431 * Default: WANObjectCache::TSE_NONE
432 * - staleTTL : Seconds to keep the key around if it is stale. The get()/getMulti()
433 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
434 * will call the regeneration callback in such cases, passing in the old value
435 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
436 * on the old value's as-of time when it is verified as still being correct.
437 * Default: 0.
438 * @note Options added in 1.28: staleTTL
439 * @return bool Success
440 */
441 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
442 $now = microtime( true );
443 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
444 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
445 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
446 $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : 0;
447
448 // Do not cache potentially uncommitted data as it might get rolled back
449 if ( !empty( $opts['pending'] ) ) {
450 $this->logger->info( 'Rejected set() for {cachekey} due to pending writes.',
451 [ 'cachekey' => $key ] );
452
453 return true; // no-op the write for being unsafe
454 }
455
456 $wrapExtra = []; // additional wrapped value fields
457 // Check if there's a risk of writing stale data after the purge tombstone expired
458 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
459 // Case A: read lag with "lockTSE"; save but record value as stale
460 if ( $lockTSE >= 0 ) {
461 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
462 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
463 // Case B: any long-running transaction; ignore this set()
464 } elseif ( $age > self::MAX_READ_LAG ) {
465 $this->logger->info( 'Rejected set() for {cachekey} due to snapshot lag.',
466 [ 'cachekey' => $key ] );
467
468 return true; // no-op the write for being unsafe
469 // Case C: high replication lag; lower TTL instead of ignoring all set()s
470 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
471 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
472 $this->logger->warning( 'Lowered set() TTL for {cachekey} due to replication lag.',
473 [ 'cachekey' => $key ] );
474 // Case D: medium length request with medium replication lag; ignore this set()
475 } else {
476 $this->logger->info( 'Rejected set() for {cachekey} due to high read lag.',
477 [ 'cachekey' => $key ] );
478
479 return true; // no-op the write for being unsafe
480 }
481 }
482
483 // Wrap that value with time/TTL/version metadata
484 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
485
486 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
487 return ( is_string( $cWrapped ) )
488 ? false // key is tombstoned; do nothing
489 : $wrapped;
490 };
491
492 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl + $staleTTL, 1 );
493 }
494
495 /**
496 * Purge a key from all datacenters
497 *
498 * This should only be called when the underlying data (being cached)
499 * changes in a significant way. This deletes the key and starts a hold-off
500 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
501 * This is done to avoid the following race condition:
502 * - a) Some DB data changes and delete() is called on a corresponding key
503 * - b) A request refills the key with a stale value from a lagged DB
504 * - c) The stale value is stuck there until the key is expired/evicted
505 *
506 * This is implemented by storing a special "tombstone" value at the cache
507 * key that this class recognizes; get() calls will return false for the key
508 * and any set() calls will refuse to replace tombstone values at the key.
509 * For this to always avoid stale value writes, the following must hold:
510 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
511 * - b) If lag is higher, the DB will have gone into read-only mode already
512 *
513 * Note that set() can also be lag-aware and lower the TTL if it's high.
514 *
515 * When using potentially long-running ACID transactions, a good pattern is
516 * to use a pre-commit hook to issue the delete. This means that immediately
517 * after commit, callers will see the tombstone in cache upon purge relay.
518 * It also avoids the following race condition:
519 * - a) T1 begins, changes a row, and calls delete()
520 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
521 * - c) T2 starts, reads the row and calls set() due to a cache miss
522 * - d) T1 finally commits
523 * - e) Stale value is stuck in cache
524 *
525 * Example usage:
526 * @code
527 * $dbw->startAtomic( __METHOD__ ); // start of request
528 * ... <execute some stuff> ...
529 * // Update the row in the DB
530 * $dbw->update( ... );
531 * $key = $cache->makeKey( 'homes', $homeId );
532 * // Purge the corresponding cache entry just before committing
533 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
534 * $cache->delete( $key );
535 * } );
536 * ... <execute some stuff> ...
537 * $dbw->endAtomic( __METHOD__ ); // end of request
538 * @endcode
539 *
540 * The $ttl parameter can be used when purging values that have not actually changed
541 * recently. For example, a cleanup script to purge cache entries does not really need
542 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
543 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
544 *
545 * If called twice on the same key, then the last hold-off TTL takes precedence. For
546 * idempotence, the $ttl should not vary for different delete() calls on the same key.
547 *
548 * @param string $key Cache key
549 * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
550 * @return bool True if the item was purged or not found, false on failure
551 */
552 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
553 $key = self::VALUE_KEY_PREFIX . $key;
554
555 if ( $ttl <= 0 ) {
556 // Publish the purge to all datacenters
557 $ok = $this->relayDelete( $key );
558 } else {
559 // Publish the purge to all datacenters
560 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE );
561 }
562
563 return $ok;
564 }
565
566 /**
567 * Fetch the value of a timestamp "check" key
568 *
569 * The key will be *initialized* to the current time if not set,
570 * so only call this method if this behavior is actually desired
571 *
572 * The timestamp can be used to check whether a cached value is valid.
573 * Callers should not assume that this returns the same timestamp in
574 * all datacenters due to relay delays.
575 *
576 * The level of staleness can roughly be estimated from this key, but
577 * if the key was evicted from cache, such calculations may show the
578 * time since expiry as ~0 seconds.
579 *
580 * Note that "check" keys won't collide with other regular keys.
581 *
582 * @param string $key
583 * @return float UNIX timestamp of the check key
584 */
585 final public function getCheckKeyTime( $key ) {
586 $key = self::TIME_KEY_PREFIX . $key;
587
588 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
589 if ( $purge !== false ) {
590 $time = $purge[self::FLD_TIME];
591 } else {
592 // Casting assures identical floats for the next getCheckKeyTime() calls
593 $now = (string)microtime( true );
594 $this->cache->add( $key,
595 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
596 self::CHECK_KEY_TTL
597 );
598 $time = (float)$now;
599 }
600
601 return $time;
602 }
603
604 /**
605 * Purge a "check" key from all datacenters, invalidating keys that use it
606 *
607 * This should only be called when the underlying data (being cached)
608 * changes in a significant way, and it is impractical to call delete()
609 * on all keys that should be changed. When get() is called on those
610 * keys, the relevant "check" keys must be supplied for this to work.
611 *
612 * The "check" key essentially represents a last-modified field.
613 * When touched, the field will be updated on all cache servers.
614 * Keys using it via get(), getMulti(), or getWithSetCallback() will
615 * be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
616 * by those methods to avoid race conditions where dependent keys get updated
617 * with stale values (e.g. from a DB replica DB).
618 *
619 * This is typically useful for keys with hardcoded names or in some cases
620 * dynamically generated names where a low number of combinations exist.
621 * When a few important keys get a large number of hits, a high cache
622 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
623 * method is less appropriate in such cases since the "time since expiry"
624 * cannot be inferred, causing any get() after the reset to treat the key
625 * as being "hot", resulting in more stale value usage.
626 *
627 * Note that "check" keys won't collide with other regular keys.
628 *
629 * @see WANObjectCache::get()
630 * @see WANObjectCache::getWithSetCallback()
631 * @see WANObjectCache::resetCheckKey()
632 *
633 * @param string $key Cache key
634 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
635 * @return bool True if the item was purged or not found, false on failure
636 */
637 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
638 // Publish the purge to all datacenters
639 return $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
640 }
641
642 /**
643 * Delete a "check" key from all datacenters, invalidating keys that use it
644 *
645 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
646 * or getWithSetCallback() will be invalidated. The differences are:
647 * - a) The "check" key will be deleted from all caches and lazily
648 * re-initialized when accessed (rather than set everywhere)
649 * - b) Thus, dependent keys will be known to be invalid, but not
650 * for how long (they are treated as "just" purged), which
651 * effects any lockTSE logic in getWithSetCallback()
652 * - c) Since "check" keys are initialized only on the server the key hashes
653 * to, any temporary ejection of that server will cause the value to be
654 * seen as purged as a new server will initialize the "check" key.
655 *
656 * The advantage is that this does not place high TTL keys on every cache
657 * server, making it better for code that will cache many different keys
658 * and either does not use lockTSE or uses a low enough TTL anyway.
659 *
660 * This is typically useful for keys with dynamically generated names
661 * where a high number of combinations exist.
662 *
663 * Note that "check" keys won't collide with other regular keys.
664 *
665 * @see WANObjectCache::get()
666 * @see WANObjectCache::getWithSetCallback()
667 * @see WANObjectCache::touchCheckKey()
668 *
669 * @param string $key Cache key
670 * @return bool True if the item was purged or not found, false on failure
671 */
672 final public function resetCheckKey( $key ) {
673 // Publish the purge to all datacenters
674 return $this->relayDelete( self::TIME_KEY_PREFIX . $key );
675 }
676
677 /**
678 * Method to fetch/regenerate cache keys
679 *
680 * On cache miss, the key will be set to the callback result via set()
681 * (unless the callback returns false) and that result will be returned.
682 * The arguments supplied to the callback are:
683 * - $oldValue : current cache value or false if not present
684 * - &$ttl : a reference to the TTL which can be altered
685 * - &$setOpts : a reference to options for set() which can be altered
686 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
687 *
688 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
689 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
690 * value, but it can be used to maintain "most recent X" values that come from time or
691 * sequence based source data, provided that the "as of" id/time is tracked. Note that
692 * preemptive regeneration and $checkKeys can result in a non-false current value.
693 *
694 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
695 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
696 * regeneration will automatically be triggered using the callback.
697 *
698 * The $ttl argument and "hotTTR" option (in $opts) use time-dependant randomization
699 * to avoid stampedes. Keys that are slow to regenerate and either heavily used
700 * or subject to explicit (unpredictable) purges, may need additional mechanisms.
701 * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts).
702 * If explicit purges are needed, also:
703 * - a) Pass $key into $checkKeys
704 * - b) Use touchCheckKey( $key ) instead of delete( $key )
705 *
706 * Example usage (typical key):
707 * @code
708 * $catInfo = $cache->getWithSetCallback(
709 * // Key to store the cached value under
710 * $cache->makeKey( 'cat-attributes', $catId ),
711 * // Time-to-live (in seconds)
712 * $cache::TTL_MINUTE,
713 * // Function that derives the new key value
714 * function ( $oldValue, &$ttl, array &$setOpts ) {
715 * $dbr = wfGetDB( DB_REPLICA );
716 * // Account for any snapshot/replica DB lag
717 * $setOpts += Database::getCacheSetOptions( $dbr );
718 *
719 * return $dbr->selectRow( ... );
720 * }
721 * );
722 * @endcode
723 *
724 * Example usage (key that is expensive and hot):
725 * @code
726 * $catConfig = $cache->getWithSetCallback(
727 * // Key to store the cached value under
728 * $cache->makeKey( 'site-cat-config' ),
729 * // Time-to-live (in seconds)
730 * $cache::TTL_DAY,
731 * // Function that derives the new key value
732 * function ( $oldValue, &$ttl, array &$setOpts ) {
733 * $dbr = wfGetDB( DB_REPLICA );
734 * // Account for any snapshot/replica DB lag
735 * $setOpts += Database::getCacheSetOptions( $dbr );
736 *
737 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
738 * },
739 * [
740 * // Calling touchCheckKey() on this key invalidates the cache
741 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
742 * // Try to only let one datacenter thread manage cache updates at a time
743 * 'lockTSE' => 30,
744 * // Avoid querying cache servers multiple times in a web request
745 * 'pcTTL' => $cache::TTL_PROC_LONG
746 * ]
747 * );
748 * @endcode
749 *
750 * Example usage (key with dynamic dependencies):
751 * @code
752 * $catState = $cache->getWithSetCallback(
753 * // Key to store the cached value under
754 * $cache->makeKey( 'cat-state', $cat->getId() ),
755 * // Time-to-live (seconds)
756 * $cache::TTL_HOUR,
757 * // Function that derives the new key value
758 * function ( $oldValue, &$ttl, array &$setOpts ) {
759 * // Determine new value from the DB
760 * $dbr = wfGetDB( DB_REPLICA );
761 * // Account for any snapshot/replica DB lag
762 * $setOpts += Database::getCacheSetOptions( $dbr );
763 *
764 * return CatState::newFromResults( $dbr->select( ... ) );
765 * },
766 * [
767 * // The "check" keys that represent things the value depends on;
768 * // Calling touchCheckKey() on any of them invalidates the cache
769 * 'checkKeys' => [
770 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
771 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
772 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
773 * ]
774 * ]
775 * );
776 * @endcode
777 *
778 * Example usage (hot key holding most recent 100 events):
779 * @code
780 * $lastCatActions = $cache->getWithSetCallback(
781 * // Key to store the cached value under
782 * $cache->makeKey( 'cat-last-actions', 100 ),
783 * // Time-to-live (in seconds)
784 * 10,
785 * // Function that derives the new key value
786 * function ( $oldValue, &$ttl, array &$setOpts ) {
787 * $dbr = wfGetDB( DB_REPLICA );
788 * // Account for any snapshot/replica DB lag
789 * $setOpts += Database::getCacheSetOptions( $dbr );
790 *
791 * // Start off with the last cached list
792 * $list = $oldValue ?: [];
793 * // Fetch the last 100 relevant rows in descending order;
794 * // only fetch rows newer than $list[0] to reduce scanning
795 * $rows = iterator_to_array( $dbr->select( ... ) );
796 * // Merge them and get the new "last 100" rows
797 * return array_slice( array_merge( $new, $list ), 0, 100 );
798 * },
799 * [
800 * // Try to only let one datacenter thread manage cache updates at a time
801 * 'lockTSE' => 30,
802 * // Use a magic value when no cache value is ready rather than stampeding
803 * 'busyValue' => 'computing'
804 * ]
805 * );
806 * @endcode
807 *
808 * @see WANObjectCache::get()
809 * @see WANObjectCache::set()
810 *
811 * @param string $key Cache key made from makeKey() or makeGlobalKey()
812 * @param int $ttl Seconds to live for key updates. Special values are:
813 * - WANObjectCache::TTL_INDEFINITE: Cache forever
814 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
815 * @param callable $callback Value generation function
816 * @param array $opts Options map:
817 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
818 * touchCheckKey() or resetCheckKey() is called on any of these keys.
819 * Default: [].
820 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
821 * ago, then try to have a single thread handle cache regeneration at any given time.
822 * Other threads will try to use stale values if possible. If, on miss, the time since
823 * expiration is low, the assumption is that the key is hot and that a stampede is worth
824 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
825 * higher this is set, the higher the worst-case staleness can be.
826 * Use WANObjectCache::TSE_NONE to disable this logic.
827 * Default: WANObjectCache::TSE_NONE.
828 * - busyValue: If no value exists and another thread is currently regenerating it, use this
829 * as a fallback value (or a callback to generate such a value). This assures that cache
830 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
831 * against cache regeneration becoming very slow for some reason (greater than the TTL).
832 * Default: null.
833 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
834 * network I/O when a key is read several times. This will not cache when the callback
835 * returns false, however. Note that any purges will not be seen while process cached;
836 * since the callback should use replica DBs and they may be lagged or have snapshot
837 * isolation anyway, this should not typically matter.
838 * Default: WANObjectCache::TTL_UNCACHEABLE.
839 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
840 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
841 * large values, small yet numerous values, or some values with a high cost of eviction.
842 * It is generally preferable to use a class constant when setting this value.
843 * This has no effect unless pcTTL is used.
844 * Default: WANObjectCache::PC_PRIMARY.
845 * - version: Integer version number. This allows for callers to make breaking changes to
846 * how values are stored while maintaining compatability and correct cache purges. New
847 * versions are stored alongside older versions concurrently. Avoid storing class objects
848 * however, as this reduces compatibility (due to serialization).
849 * Default: null.
850 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
851 * This is useful if the source of a key is suspected of having possibly changed
852 * recently, and the caller wants any such changes to be reflected.
853 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
854 * - hotTTR: Expected time-till-refresh (TTR) for keys that average ~1 hit/second (1 Hz).
855 * Keys with a hit rate higher than 1Hz will refresh sooner than this TTR and vise versa.
856 * Such refreshes won't happen until keys are "ageNew" seconds old. The TTR is useful at
857 * reducing the impact of missed cache purges, since the effect of a heavily referenced
858 * key being stale is worse than that of a rarely referenced key. Unlike simply lowering
859 * $ttl, seldomly used keys are largely unaffected by this option, which makes it possible
860 * to have a high hit rate for the "long-tail" of less-used keys.
861 * Default: WANObjectCache::HOT_TTR.
862 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
863 * than this. It becomes more likely over time, becoming certain once the key is expired.
864 * Default: WANObjectCache::LOW_TTL.
865 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
866 * Default: WANObjectCache::AGE_NEW.
867 * @return mixed Value found or written to the key
868 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
869 * @note Callable type hints are not used to avoid class-autoloading
870 */
871 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
872 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
873
874 // Try the process cache if enabled and the cache callback is not within a cache callback.
875 // Process cache use in nested callbacks is not lag-safe with regard to HOLDOFF_TTL since
876 // the in-memory value is further lagged than the shared one since it uses a blind TTL.
877 if ( $pcTTL >= 0 && $this->callbackDepth == 0 ) {
878 $group = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY;
879 $procCache = $this->getProcessCache( $group );
880 $value = $procCache->get( $key );
881 } else {
882 $procCache = false;
883 $value = false;
884 }
885
886 if ( $value === false ) {
887 // Fetch the value over the network
888 if ( isset( $opts['version'] ) ) {
889 $version = $opts['version'];
890 $asOf = null;
891 $cur = $this->doGetWithSetCallback(
892 $key,
893 $ttl,
894 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
895 use ( $callback, $version ) {
896 if ( is_array( $oldValue )
897 && array_key_exists( self::VFLD_DATA, $oldValue )
898 ) {
899 $oldData = $oldValue[self::VFLD_DATA];
900 } else {
901 // VFLD_DATA is not set if an old, unversioned, key is present
902 $oldData = false;
903 }
904
905 return [
906 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
907 self::VFLD_VERSION => $version
908 ];
909 },
910 $opts,
911 $asOf
912 );
913 if ( $cur[self::VFLD_VERSION] === $version ) {
914 // Value created or existed before with version; use it
915 $value = $cur[self::VFLD_DATA];
916 } else {
917 // Value existed before with a different version; use variant key.
918 // Reflect purges to $key by requiring that this key value be newer.
919 $value = $this->doGetWithSetCallback(
920 'cache-variant:' . md5( $key ) . ":$version",
921 $ttl,
922 $callback,
923 // Regenerate value if not newer than $key
924 [ 'version' => null, 'minAsOf' => $asOf ] + $opts
925 );
926 }
927 } else {
928 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
929 }
930
931 // Update the process cache if enabled
932 if ( $procCache && $value !== false ) {
933 $procCache->set( $key, $value, $pcTTL );
934 }
935 }
936
937 return $value;
938 }
939
940 /**
941 * Do the actual I/O for getWithSetCallback() when needed
942 *
943 * @see WANObjectCache::getWithSetCallback()
944 *
945 * @param string $key
946 * @param int $ttl
947 * @param callback $callback
948 * @param array $opts Options map for getWithSetCallback()
949 * @param float &$asOf Cache generation timestamp of returned value [returned]
950 * @return mixed
951 * @note Callable type hints are not used to avoid class-autoloading
952 */
953 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
954 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
955 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
956 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
957 $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
958 $popWindow = isset( $opts['hotTTR'] ) ? $opts['hotTTR'] : self::HOT_TTR;
959 $ageNew = isset( $opts['ageNew'] ) ? $opts['ageNew'] : self::AGE_NEW;
960 $minTime = isset( $opts['minAsOf'] ) ? $opts['minAsOf'] : self::MIN_TIMESTAMP_NONE;
961 $versioned = isset( $opts['version'] );
962
963 // Get a collection name to describe this class of key
964 $kClass = $this->determineKeyClass( $key );
965
966 // Get the current key value
967 $curTTL = null;
968 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
969 $value = $cValue; // return value
970
971 $preCallbackTime = microtime( true );
972 // Determine if a cached value regeneration is needed or desired
973 if ( $value !== false
974 && $curTTL > 0
975 && $this->isValid( $value, $versioned, $asOf, $minTime )
976 && !$this->worthRefreshExpiring( $curTTL, $lowTTL )
977 && !$this->worthRefreshPopular( $asOf, $ageNew, $popWindow, $preCallbackTime )
978 ) {
979 $this->stats->increment( "wanobjectcache.$kClass.hit.good" );
980
981 return $value;
982 }
983
984 // A deleted key with a negative TTL left must be tombstoned
985 $isTombstone = ( $curTTL !== null && $value === false );
986 if ( $isTombstone && $lockTSE <= 0 ) {
987 // Use the INTERIM value for tombstoned keys to reduce regeneration load
988 $lockTSE = 1;
989 }
990 // Assume a key is hot if requested soon after invalidation
991 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
992 // Use the mutex if there is no value and a busy fallback is given
993 $checkBusy = ( $busyValue !== null && $value === false );
994 // Decide whether a single thread should handle regenerations.
995 // This avoids stampedes when $checkKeys are bumped and when preemptive
996 // renegerations take too long. It also reduces regenerations while $key
997 // is tombstoned. This balances cache freshness with avoiding DB load.
998 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
999
1000 $lockAcquired = false;
1001 if ( $useMutex ) {
1002 // Acquire a datacenter-local non-blocking lock
1003 if ( $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
1004 // Lock acquired; this thread should update the key
1005 $lockAcquired = true;
1006 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1007 $this->stats->increment( "wanobjectcache.$kClass.hit.stale" );
1008 // If it cannot be acquired; then the stale value can be used
1009 return $value;
1010 } else {
1011 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
1012 // For hot keys, either another thread has the lock or the lock failed;
1013 // use the INTERIM value from the last thread that regenerated it.
1014 $value = $this->getInterimValue( $key, $versioned, $minTime, $asOf );
1015 if ( $value !== false ) {
1016 $this->stats->increment( "wanobjectcache.$kClass.hit.volatile" );
1017
1018 return $value;
1019 }
1020 // Use the busy fallback value if nothing else
1021 if ( $busyValue !== null ) {
1022 $this->stats->increment( "wanobjectcache.$kClass.miss.busy" );
1023
1024 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
1025 }
1026 }
1027 }
1028
1029 if ( !is_callable( $callback ) ) {
1030 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
1031 }
1032
1033 // Generate the new value from the callback...
1034 $setOpts = [];
1035 ++$this->callbackDepth;
1036 try {
1037 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
1038 } finally {
1039 --$this->callbackDepth;
1040 }
1041 $valueIsCacheable = ( $value !== false && $ttl >= 0 );
1042
1043 // When delete() is called, writes are write-holed by the tombstone,
1044 // so use a special INTERIM key to pass the new value around threads.
1045 if ( ( $isTombstone && $lockTSE > 0 ) && $valueIsCacheable ) {
1046 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
1047 $newAsOf = microtime( true );
1048 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
1049 // Avoid using set() to avoid pointless mcrouter broadcasting
1050 $this->setInterimValue( $key, $wrapped, $tempTTL );
1051 }
1052
1053 if ( $valueIsCacheable ) {
1054 $setOpts['lockTSE'] = $lockTSE;
1055 // Use best known "since" timestamp if not provided
1056 $setOpts += [ 'since' => $preCallbackTime ];
1057 // Update the cache; this will fail if the key is tombstoned
1058 $this->set( $key, $value, $ttl, $setOpts );
1059 }
1060
1061 if ( $lockAcquired ) {
1062 // Avoid using delete() to avoid pointless mcrouter broadcasting
1063 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, (int)$preCallbackTime - 60 );
1064 }
1065
1066 $this->stats->increment( "wanobjectcache.$kClass.miss.compute" );
1067
1068 return $value;
1069 }
1070
1071 /**
1072 * @param string $key
1073 * @param bool $versioned
1074 * @param float $minTime
1075 * @param mixed $asOf
1076 * @return mixed
1077 */
1078 protected function getInterimValue( $key, $versioned, $minTime, &$asOf ) {
1079 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
1080 list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
1081 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
1082 $asOf = $wrapped[self::FLD_TIME];
1083
1084 return $value;
1085 }
1086
1087 return false;
1088 }
1089
1090 /**
1091 * @param string $key
1092 * @param array $wrapped
1093 * @param int $tempTTL
1094 */
1095 protected function setInterimValue( $key, $wrapped, $tempTTL ) {
1096 $this->cache->merge(
1097 self::INTERIM_KEY_PREFIX . $key,
1098 function () use ( $wrapped ) {
1099 return $wrapped;
1100 },
1101 $tempTTL,
1102 1
1103 );
1104 }
1105
1106 /**
1107 * Method to fetch multiple cache keys at once with regeneration
1108 *
1109 * This works the same as getWithSetCallback() except:
1110 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1111 * - b) The $callback argument expects a callback taking the following arguments:
1112 * - $id: ID of an entity to query
1113 * - $oldValue : the prior cache value or false if none was present
1114 * - &$ttl : a reference to the new value TTL in seconds
1115 * - &$setOpts : a reference to options for set() which can be altered
1116 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present
1117 * Aside from the additional $id argument, the other arguments function the same
1118 * way they do in getWithSetCallback().
1119 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1120 *
1121 * @see WANObjectCache::getWithSetCallback()
1122 * @see WANObjectCache::getMultiWithUnionSetCallback()
1123 *
1124 * Example usage:
1125 * @code
1126 * $rows = $cache->getMultiWithSetCallback(
1127 * // Map of cache keys to entity IDs
1128 * $cache->makeMultiKeys(
1129 * $this->fileVersionIds(),
1130 * function ( $id, WANObjectCache $cache ) {
1131 * return $cache->makeKey( 'file-version', $id );
1132 * }
1133 * ),
1134 * // Time-to-live (in seconds)
1135 * $cache::TTL_DAY,
1136 * // Function that derives the new key value
1137 * function ( $id, $oldValue, &$ttl, array &$setOpts ) {
1138 * $dbr = wfGetDB( DB_REPLICA );
1139 * // Account for any snapshot/replica DB lag
1140 * $setOpts += Database::getCacheSetOptions( $dbr );
1141 *
1142 * // Load the row for this file
1143 * $queryInfo = File::getQueryInfo();
1144 * $row = $dbr->selectRow(
1145 * $queryInfo['tables'],
1146 * $queryInfo['fields'],
1147 * [ 'id' => $id ],
1148 * __METHOD__,
1149 * [],
1150 * $queryInfo['joins']
1151 * );
1152 *
1153 * return $row ? (array)$row : false;
1154 * },
1155 * [
1156 * // Process cache for 30 seconds
1157 * 'pcTTL' => 30,
1158 * // Use a dedicated 500 item cache (initialized on-the-fly)
1159 * 'pcGroup' => 'file-versions:500'
1160 * ]
1161 * );
1162 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1163 * @endcode
1164 *
1165 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1166 * @param int $ttl Seconds to live for key updates
1167 * @param callable $callback Callback the yields entity regeneration callbacks
1168 * @param array $opts Options map
1169 * @return array Map of (cache key => value) in the same order as $keyedIds
1170 * @since 1.28
1171 */
1172 final public function getMultiWithSetCallback(
1173 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1174 ) {
1175 $valueKeys = array_keys( $keyedIds->getArrayCopy() );
1176 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
1177
1178 // Load required keys into process cache in one go
1179 $this->warmupCache = $this->getRawKeysForWarmup(
1180 $this->getNonProcessCachedKeys( $valueKeys, $opts ),
1181 $checkKeys
1182 );
1183 $this->warmupKeyMisses = 0;
1184
1185 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1186 $id = null; // current entity ID
1187 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf ) use ( $callback, &$id ) {
1188 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1189 };
1190
1191 $values = [];
1192 foreach ( $keyedIds as $key => $id ) { // preserve order
1193 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1194 }
1195
1196 $this->warmupCache = [];
1197
1198 return $values;
1199 }
1200
1201 /**
1202 * Method to fetch/regenerate multiple cache keys at once
1203 *
1204 * This works the same as getWithSetCallback() except:
1205 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1206 * - b) The $callback argument expects a callback returning a map of (ID => new value)
1207 * for all entity IDs in $regenById and it takes the following arguments:
1208 * - $ids: a list of entity IDs to regenerate
1209 * - &$ttls: a reference to the (entity ID => new TTL) map
1210 * - &$setOpts: a reference to options for set() which can be altered
1211 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1212 * - d) The "lockTSE" and "busyValue" options are ignored
1213 *
1214 * @see WANObjectCache::getWithSetCallback()
1215 * @see WANObjectCache::getMultiWithSetCallback()
1216 *
1217 * Example usage:
1218 * @code
1219 * $rows = $cache->getMultiWithUnionSetCallback(
1220 * // Map of cache keys to entity IDs
1221 * $cache->makeMultiKeys(
1222 * $this->fileVersionIds(),
1223 * function ( $id, WANObjectCache $cache ) {
1224 * return $cache->makeKey( 'file-version', $id );
1225 * }
1226 * ),
1227 * // Time-to-live (in seconds)
1228 * $cache::TTL_DAY,
1229 * // Function that derives the new key value
1230 * function ( array $ids, array &$ttls, array &$setOpts ) {
1231 * $dbr = wfGetDB( DB_REPLICA );
1232 * // Account for any snapshot/replica DB lag
1233 * $setOpts += Database::getCacheSetOptions( $dbr );
1234 *
1235 * // Load the rows for these files
1236 * $rows = [];
1237 * $queryInfo = File::getQueryInfo();
1238 * $res = $dbr->select(
1239 * $queryInfo['tables'],
1240 * $queryInfo['fields'],
1241 * [ 'id' => $ids ],
1242 * __METHOD__,
1243 * [],
1244 * $queryInfo['joins']
1245 * );
1246 * foreach ( $res as $row ) {
1247 * $rows[$row->id] = $row;
1248 * $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
1249 * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
1250 * }
1251 *
1252 * return $rows;
1253 * },
1254 * ]
1255 * );
1256 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1257 * @endcode
1258 *
1259 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1260 * @param int $ttl Seconds to live for key updates
1261 * @param callable $callback Callback the yields entity regeneration callbacks
1262 * @param array $opts Options map
1263 * @return array Map of (cache key => value) in the same order as $keyedIds
1264 * @since 1.30
1265 */
1266 final public function getMultiWithUnionSetCallback(
1267 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1268 ) {
1269 $idsByValueKey = $keyedIds->getArrayCopy();
1270 $valueKeys = array_keys( $idsByValueKey );
1271 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
1272 unset( $opts['lockTSE'] ); // incompatible
1273 unset( $opts['busyValue'] ); // incompatible
1274
1275 // Load required keys into process cache in one go
1276 $keysGet = $this->getNonProcessCachedKeys( $valueKeys, $opts );
1277 $this->warmupCache = $this->getRawKeysForWarmup( $keysGet, $checkKeys );
1278 $this->warmupKeyMisses = 0;
1279
1280 // IDs of entities known to be in need of regeneration
1281 $idsRegen = [];
1282
1283 // Find out which keys are missing/deleted/stale
1284 $curTTLs = [];
1285 $asOfs = [];
1286 $curByKey = $this->getMulti( $keysGet, $curTTLs, $checkKeys, $asOfs );
1287 foreach ( $keysGet as $key ) {
1288 if ( !array_key_exists( $key, $curByKey ) || $curTTLs[$key] < 0 ) {
1289 $idsRegen[] = $idsByValueKey[$key];
1290 }
1291 }
1292
1293 // Run the callback to populate the regeneration value map for all required IDs
1294 $newSetOpts = [];
1295 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
1296 $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
1297
1298 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1299 $id = null; // current entity ID
1300 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1301 use ( $callback, &$id, $newValsById, $newTTLsById, $newSetOpts )
1302 {
1303 if ( array_key_exists( $id, $newValsById ) ) {
1304 // Value was already regerated as expected, so use the value in $newValsById
1305 $newValue = $newValsById[$id];
1306 $ttl = $newTTLsById[$id];
1307 $setOpts = $newSetOpts;
1308 } else {
1309 // Pre-emptive/popularity refresh and version mismatch cases are not detected
1310 // above and thus $newValsById has no entry. Run $callback on this single entity.
1311 $ttls = [ $id => $ttl ];
1312 $newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
1313 $ttl = $ttls[$id];
1314 }
1315
1316 return $newValue;
1317 };
1318
1319 // Run the cache-aside logic using warmupCache instead of persistent cache queries
1320 $values = [];
1321 foreach ( $idsByValueKey as $key => $id ) { // preserve order
1322 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1323 }
1324
1325 $this->warmupCache = [];
1326
1327 return $values;
1328 }
1329
1330 /**
1331 * Locally set a key to expire soon if it is stale based on $purgeTimestamp
1332 *
1333 * This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids
1334 * broadcasting in mcrouter setups and also avoids races with new tombstones.
1335 *
1336 * @param string $key Cache key
1337 * @param int $purgeTimestamp UNIX timestamp of purge
1338 * @param bool &$isStale Whether the key is stale
1339 * @return bool Success
1340 * @since 1.28
1341 */
1342 public function reap( $key, $purgeTimestamp, &$isStale = false ) {
1343 $minAsOf = $purgeTimestamp + self::HOLDOFF_TTL;
1344 $wrapped = $this->cache->get( self::VALUE_KEY_PREFIX . $key );
1345 if ( is_array( $wrapped ) && $wrapped[self::FLD_TIME] < $minAsOf ) {
1346 $isStale = true;
1347 $this->logger->warning( "Reaping stale value key '$key'." );
1348 $ttlReap = self::HOLDOFF_TTL; // avoids races with tombstone creation
1349 $ok = $this->cache->changeTTL( self::VALUE_KEY_PREFIX . $key, $ttlReap );
1350 if ( !$ok ) {
1351 $this->logger->error( "Could not complete reap of key '$key'." );
1352 }
1353
1354 return $ok;
1355 }
1356
1357 $isStale = false;
1358
1359 return true;
1360 }
1361
1362 /**
1363 * Locally set a "check" key to expire soon if it is stale based on $purgeTimestamp
1364 *
1365 * @param string $key Cache key
1366 * @param int $purgeTimestamp UNIX timestamp of purge
1367 * @param bool &$isStale Whether the key is stale
1368 * @return bool Success
1369 * @since 1.28
1370 */
1371 public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
1372 $purge = $this->parsePurgeValue( $this->cache->get( self::TIME_KEY_PREFIX . $key ) );
1373 if ( $purge && $purge[self::FLD_TIME] < $purgeTimestamp ) {
1374 $isStale = true;
1375 $this->logger->warning( "Reaping stale check key '$key'." );
1376 $ok = $this->cache->changeTTL( self::TIME_KEY_PREFIX . $key, 1 );
1377 if ( !$ok ) {
1378 $this->logger->error( "Could not complete reap of check key '$key'." );
1379 }
1380
1381 return $ok;
1382 }
1383
1384 $isStale = false;
1385
1386 return false;
1387 }
1388
1389 /**
1390 * @see BagOStuff::makeKey()
1391 * @param string $class Key class
1392 * @param string $component [optional] Key component (starting with a key collection name)
1393 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1394 * @since 1.27
1395 */
1396 public function makeKey( $class, $component = null ) {
1397 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1398 }
1399
1400 /**
1401 * @see BagOStuff::makeGlobalKey()
1402 * @param string $class Key class
1403 * @param string $component [optional] Key component (starting with a key collection name)
1404 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1405 * @since 1.27
1406 */
1407 public function makeGlobalKey( $class, $component = null ) {
1408 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1409 }
1410
1411 /**
1412 * @param array $entities List of entity IDs
1413 * @param callable $keyFunc Callback yielding a key from (entity ID, this WANObjectCache)
1414 * @return ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
1415 * @since 1.28
1416 */
1417 public function makeMultiKeys( array $entities, callable $keyFunc ) {
1418 $map = [];
1419 foreach ( $entities as $entity ) {
1420 $map[$keyFunc( $entity, $this )] = $entity;
1421 }
1422
1423 return new ArrayIterator( $map );
1424 }
1425
1426 /**
1427 * Get the "last error" registered; clearLastError() should be called manually
1428 * @return int ERR_* class constant for the "last error" registry
1429 */
1430 final public function getLastError() {
1431 if ( $this->lastRelayError ) {
1432 // If the cache and the relayer failed, focus on the latter.
1433 // An update not making it to the relayer means it won't show up
1434 // in other DCs (nor will consistent re-hashing see up-to-date values).
1435 // On the other hand, if just the cache update failed, then it should
1436 // eventually be applied by the relayer.
1437 return $this->lastRelayError;
1438 }
1439
1440 $code = $this->cache->getLastError();
1441 switch ( $code ) {
1442 case BagOStuff::ERR_NONE:
1443 return self::ERR_NONE;
1444 case BagOStuff::ERR_NO_RESPONSE:
1445 return self::ERR_NO_RESPONSE;
1446 case BagOStuff::ERR_UNREACHABLE:
1447 return self::ERR_UNREACHABLE;
1448 default:
1449 return self::ERR_UNEXPECTED;
1450 }
1451 }
1452
1453 /**
1454 * Clear the "last error" registry
1455 */
1456 final public function clearLastError() {
1457 $this->cache->clearLastError();
1458 $this->lastRelayError = self::ERR_NONE;
1459 }
1460
1461 /**
1462 * Clear the in-process caches; useful for testing
1463 *
1464 * @since 1.27
1465 */
1466 public function clearProcessCache() {
1467 $this->processCaches = [];
1468 }
1469
1470 /**
1471 * @param int $flag ATTR_* class constant
1472 * @return int QOS_* class constant
1473 * @since 1.28
1474 */
1475 public function getQoS( $flag ) {
1476 return $this->cache->getQoS( $flag );
1477 }
1478
1479 /**
1480 * Get a TTL that is higher for objects that have not changed recently
1481 *
1482 * This is useful for keys that get explicit purges and DB or purge relay
1483 * lag is a potential concern (especially how it interacts with CDN cache)
1484 *
1485 * Example usage:
1486 * @code
1487 * // Last-modified time of page
1488 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1489 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1490 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1491 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1492 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1493 * @endcode
1494 *
1495 * @param int|float $mtime UNIX timestamp
1496 * @param int $maxTTL Maximum TTL (seconds)
1497 * @param int $minTTL Minimum TTL (seconds); Default: 30
1498 * @param float $factor Value in the range (0,1); Default: .2
1499 * @return int Adaptive TTL
1500 * @since 1.28
1501 */
1502 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
1503 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
1504 $mtime = (int)$mtime; // handle fractional seconds and string integers
1505 }
1506
1507 if ( !is_int( $mtime ) || $mtime <= 0 ) {
1508 return $minTTL; // no last-modified time provided
1509 }
1510
1511 $age = time() - $mtime;
1512
1513 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1514 }
1515
1516 /**
1517 * @return int Number of warmup key cache misses last round
1518 * @since 1.30
1519 */
1520 public function getWarmupKeyMisses() {
1521 return $this->warmupKeyMisses;
1522 }
1523
1524 /**
1525 * Do the actual async bus purge of a key
1526 *
1527 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1528 *
1529 * @param string $key Cache key
1530 * @param int $ttl How long to keep the tombstone [seconds]
1531 * @param int $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1532 * @return bool Success
1533 */
1534 protected function relayPurge( $key, $ttl, $holdoff ) {
1535 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1536 // This handles the mcrouter and the single-DC case
1537 $ok = $this->cache->set( $key,
1538 $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
1539 $ttl
1540 );
1541 } else {
1542 $event = $this->cache->modifySimpleRelayEvent( [
1543 'cmd' => 'set',
1544 'key' => $key,
1545 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1546 'ttl' => max( $ttl, 1 ),
1547 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1548 ] );
1549
1550 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1551 if ( !$ok ) {
1552 $this->lastRelayError = self::ERR_RELAY;
1553 }
1554 }
1555
1556 return $ok;
1557 }
1558
1559 /**
1560 * Do the actual async bus delete of a key
1561 *
1562 * @param string $key Cache key
1563 * @return bool Success
1564 */
1565 protected function relayDelete( $key ) {
1566 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1567 // This handles the mcrouter and the single-DC case
1568 $ok = $this->cache->delete( $key );
1569 } else {
1570 $event = $this->cache->modifySimpleRelayEvent( [
1571 'cmd' => 'delete',
1572 'key' => $key,
1573 ] );
1574
1575 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1576 if ( !$ok ) {
1577 $this->lastRelayError = self::ERR_RELAY;
1578 }
1579 }
1580
1581 return $ok;
1582 }
1583
1584 /**
1585 * Check if a key is nearing expiration and thus due for randomized regeneration
1586 *
1587 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
1588 * of returning true increases steadily from 0% to 100% as the $curTTL
1589 * moves from $lowTTL to 0 seconds. This handles widely varying
1590 * levels of cache access traffic.
1591 *
1592 * @param float $curTTL Approximate TTL left on the key if present
1593 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1594 * @return bool
1595 */
1596 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1597 if ( $curTTL >= $lowTTL ) {
1598 return false;
1599 } elseif ( $curTTL <= 0 ) {
1600 return true;
1601 }
1602
1603 $chance = ( 1 - $curTTL / $lowTTL );
1604
1605 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1606 }
1607
1608 /**
1609 * Check if a key is due for randomized regeneration due to its popularity
1610 *
1611 * This is used so that popular keys can preemptively refresh themselves for higher
1612 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
1613 * in cache with their high nominal TTL. This means popular keys keep good consistency,
1614 * whether the data changes frequently or not, and long-tail keys get to stay in cache
1615 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
1616 *
1617 * @param float $asOf UNIX timestamp of the value
1618 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
1619 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
1620 * @param float $now The current UNIX timestamp
1621 * @return bool
1622 */
1623 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
1624 $age = $now - $asOf;
1625 $timeOld = $age - $ageNew;
1626 if ( $timeOld <= 0 ) {
1627 return false;
1628 }
1629
1630 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
1631 // Note that the "expected # of refreshes" for the ramp-up time range is half of what it
1632 // would be if P(refresh) was at its full value during that time range.
1633 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
1634 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1635 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1636 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1637 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
1638
1639 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1640 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
1641
1642 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1643 }
1644
1645 /**
1646 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1647 *
1648 * @param array $value
1649 * @param bool $versioned
1650 * @param float $asOf The time $value was generated
1651 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1652 * @return bool
1653 */
1654 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1655 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1656 return false;
1657 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1658 return false;
1659 }
1660
1661 return true;
1662 }
1663
1664 /**
1665 * Do not use this method outside WANObjectCache
1666 *
1667 * @param mixed $value
1668 * @param int $ttl [0=forever]
1669 * @param float $now Unix Current timestamp just before calling set()
1670 * @return array
1671 */
1672 protected function wrap( $value, $ttl, $now ) {
1673 return [
1674 self::FLD_VERSION => self::VERSION,
1675 self::FLD_VALUE => $value,
1676 self::FLD_TTL => $ttl,
1677 self::FLD_TIME => $now
1678 ];
1679 }
1680
1681 /**
1682 * Do not use this method outside WANObjectCache
1683 *
1684 * @param array|string|bool $wrapped
1685 * @param float $now Unix Current timestamp (preferrably pre-query)
1686 * @return array (mixed; false if absent/tombstoned/invalid, current time left)
1687 */
1688 protected function unwrap( $wrapped, $now ) {
1689 // Check if the value is a tombstone
1690 $purge = self::parsePurgeValue( $wrapped );
1691 if ( $purge !== false ) {
1692 // Purged values should always have a negative current $ttl
1693 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1694 return [ false, $curTTL ];
1695 }
1696
1697 if ( !is_array( $wrapped ) // not found
1698 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1699 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1700 ) {
1701 return [ false, null ];
1702 }
1703
1704 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1705 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1706 // Treat as expired, with the cache time as the expiration
1707 $age = $now - $wrapped[self::FLD_TIME];
1708 $curTTL = min( -$age, self::TINY_NEGATIVE );
1709 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1710 // Get the approximate time left on the key
1711 $age = $now - $wrapped[self::FLD_TIME];
1712 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1713 } else {
1714 // Key had no TTL, so the time left is unbounded
1715 $curTTL = INF;
1716 }
1717
1718 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1719 }
1720
1721 /**
1722 * @param array $keys
1723 * @param string $prefix
1724 * @return string[]
1725 */
1726 protected static function prefixCacheKeys( array $keys, $prefix ) {
1727 $res = [];
1728 foreach ( $keys as $key ) {
1729 $res[] = $prefix . $key;
1730 }
1731
1732 return $res;
1733 }
1734
1735 /**
1736 * @param string $key String of the format <scope>:<class>[:<class or variable>]...
1737 * @return string
1738 */
1739 protected function determineKeyClass( $key ) {
1740 $parts = explode( ':', $key );
1741
1742 return isset( $parts[1] ) ? $parts[1] : $parts[0]; // sanity
1743 }
1744
1745 /**
1746 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1747 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1748 * or false if value isn't a valid purge value
1749 */
1750 protected static function parsePurgeValue( $value ) {
1751 if ( !is_string( $value ) ) {
1752 return false;
1753 }
1754 $segments = explode( ':', $value, 3 );
1755 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1756 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1757 ) {
1758 return false;
1759 }
1760 if ( !isset( $segments[2] ) ) {
1761 // Back-compat with old purge values without holdoff
1762 $segments[2] = self::HOLDOFF_TTL;
1763 }
1764 return [
1765 self::FLD_TIME => (float)$segments[1],
1766 self::FLD_HOLDOFF => (int)$segments[2],
1767 ];
1768 }
1769
1770 /**
1771 * @param float $timestamp
1772 * @param int $holdoff In seconds
1773 * @return string Wrapped purge value
1774 */
1775 protected function makePurgeValue( $timestamp, $holdoff ) {
1776 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1777 }
1778
1779 /**
1780 * @param string $group
1781 * @return HashBagOStuff
1782 */
1783 protected function getProcessCache( $group ) {
1784 if ( !isset( $this->processCaches[$group] ) ) {
1785 list( , $n ) = explode( ':', $group );
1786 $this->processCaches[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
1787 }
1788
1789 return $this->processCaches[$group];
1790 }
1791
1792 /**
1793 * @param array $keys
1794 * @param array $opts
1795 * @return array List of keys
1796 */
1797 private function getNonProcessCachedKeys( array $keys, array $opts ) {
1798 $keysFound = [];
1799 if ( isset( $opts['pcTTL'] ) && $opts['pcTTL'] > 0 && $this->callbackDepth == 0 ) {
1800 $pcGroup = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY;
1801 $procCache = $this->getProcessCache( $pcGroup );
1802 foreach ( $keys as $key ) {
1803 if ( $procCache->get( $key ) !== false ) {
1804 $keysFound[] = $key;
1805 }
1806 }
1807 }
1808
1809 return array_diff( $keys, $keysFound );
1810 }
1811
1812 /**
1813 * @param array $keys
1814 * @param array $checkKeys
1815 * @return array Map of (cache key => mixed)
1816 */
1817 private function getRawKeysForWarmup( array $keys, array $checkKeys ) {
1818 if ( !$keys ) {
1819 return [];
1820 }
1821
1822 $keysWarmUp = [];
1823 // Get all the value keys to fetch...
1824 foreach ( $keys as $key ) {
1825 $keysWarmUp[] = self::VALUE_KEY_PREFIX . $key;
1826 }
1827 // Get all the check keys to fetch...
1828 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
1829 if ( is_int( $i ) ) {
1830 // Single check key that applies to all value keys
1831 $keysWarmUp[] = self::TIME_KEY_PREFIX . $checkKeyOrKeys;
1832 } else {
1833 // List of check keys that apply to value key $i
1834 $keysWarmUp = array_merge(
1835 $keysWarmUp,
1836 self::prefixCacheKeys( $checkKeyOrKeys, self::TIME_KEY_PREFIX )
1837 );
1838 }
1839 }
1840
1841 $warmupCache = $this->cache->getMulti( $keysWarmUp );
1842 $warmupCache += array_fill_keys( $keysWarmUp, false );
1843
1844 return $warmupCache;
1845 }
1846 }