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