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