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