Merge "Title: Title::getSubpage should not lose the interwiki prefix"
[lhc/web/wiklou.git] / includes / libs / objectcache / WANObjectCache.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Cache
20 */
21
22 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26
27 /**
28 * Multi-datacenter aware caching interface
29 *
30 * ### Using WANObjectCache
31 *
32 * All operations go to the local datacenter cache, except for delete(),
33 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
34 *
35 * This class is intended for caching data from primary stores.
36 * If the get() method does not return a value, then the caller
37 * should query the new value and backfill the cache using set().
38 * The preferred way to do this logic is through getWithSetCallback().
39 * When querying the store on cache miss, the closest DB replica
40 * should be used. Try to avoid heavyweight DB master or quorum reads.
41 *
42 * To ensure consumers of the cache see new values in a timely manner,
43 * you either need to follow either the validation strategy, or the
44 * purge strategy.
45 *
46 * The validation strategy refers to the natural avoidance of stale data
47 * by one of the following means:
48 *
49 * - A) The cached value is immutable.
50 * If the consumer has access to an identifier that uniquely describes a value,
51 * cached value need not change. Instead, the key can change. This also allows
52 * all servers to access their perceived current version. This is important
53 * in context of multiple deployed versions of your application and/or cross-dc
54 * database replication, to ensure deterministic values without oscillation.
55 * - B) Validity is checked against the source after get().
56 * This is the inverse of A. The unique identifier is embedded inside the value
57 * and validated after on retreival. If outdated, the value is recomputed.
58 * - C) The value is cached with a modest TTL (without validation).
59 * If value recomputation is reasonably performant, and the value is allowed to
60 * be stale, one should consider using TTL only – using the value's age as
61 * method of validation.
62 *
63 * The purge strategy refers to the the approach whereby your application knows that
64 * source data has changed and can react by purging the relevant cache keys.
65 * As purges are expensive, this strategy should be avoided if possible.
66 * The simplest purge method is delete().
67 *
68 * No matter which strategy you choose, callers must not rely on updates or purges
69 * being immediately visible to other servers. It should be treated similarly as
70 * one would a database replica.
71 *
72 * The need for immediate updates should be avoided. If needed, solutions must be
73 * sought outside WANObjectCache.
74 *
75 * ### Deploying WANObjectCache
76 *
77 * There are two supported ways to set up broadcasted operations:
78 *
79 * - A) Set up mcrouter as the underlying cache backend, using a memcached BagOStuff class
80 * for the 'cache' parameter. The 'region' and 'cluster' parameters must be provided
81 * and 'mcrouterAware' must be set to `true`.
82 * Configure mcrouter as follows:
83 * - 1) Use Route Prefixing based on region (datacenter) and cache cluster.
84 * See https://github.com/facebook/mcrouter/wiki/Routing-Prefix and
85 * https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup.
86 * - 2) To increase the consistency of delete() and touchCheckKey() during cache
87 * server membership changes, you can use the OperationSelectorRoute to
88 * configure 'set' and 'delete' operations to go to all servers in the cache
89 * cluster, instead of just one server determined by hashing.
90 * See https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles.
91 * - B) Set up dynomite as a cache middleware between the web servers and either memcached
92 * or redis and use it as the underlying cache backend, using a memcached BagOStuff
93 * class for the 'cache' parameter. This will broadcast all key setting operations,
94 * not just purges, which can be useful for cache warming. Writes are eventually
95 * consistent via the Dynamo replication model. See https://github.com/Netflix/dynomite.
96 *
97 * Broadcasted operations like delete() and touchCheckKey() are intended to run
98 * immediately in the local datacenter and asynchronously in remote datacenters.
99 *
100 * This means that callers in all datacenters may see older values for however many
101 * milliseconds that the purge took to reach that datacenter. As with any cache, this
102 * should not be relied on for cases where reads are used to determine writes to source
103 * (e.g. non-cache) data stores, except when reading immutable data.
104 *
105 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
106 * to avoid collisions with keys that are not wrapped as metadata arrays. The
107 * prefixes are as follows:
108 * - a) "WANCache:v" : used for regular value keys
109 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
110 * - c) "WANCache:t" : used for storing timestamp "check" keys
111 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
112 *
113 * @ingroup Cache
114 * @since 1.26
115 */
116 class WANObjectCache implements IExpiringStore, IStoreKeyEncoder, LoggerAwareInterface {
117 /** @var BagOStuff The local datacenter cache */
118 protected $cache;
119 /** @var MapCacheLRU[] Map of group PHP instance caches */
120 protected $processCaches = [];
121 /** @bar bool Whether to use mcrouter key prefixing for routing */
122 protected $mcrouterAware;
123 /** @var string Physical region for mcrouter use */
124 protected $region;
125 /** @var string Cache cluster name for mcrouter use */
126 protected $cluster;
127 /** @var LoggerInterface */
128 protected $logger;
129 /** @var StatsdDataFactoryInterface */
130 protected $stats;
131 /** @var bool Whether to use "interim" caching while keys are tombstoned */
132 protected $useInterimHoldOffCaching = true;
133 /** @var callable|null Function that takes a WAN cache callback and runs it later */
134 protected $asyncHandler;
135 /** @var float Unix timestamp of the oldest possible valid values */
136 protected $epoch;
137
138 /** @var int Callback stack depth for getWithSetCallback() */
139 private $callbackDepth = 0;
140 /** @var mixed[] Temporary warm-up cache */
141 private $warmupCache = [];
142 /** @var int Key fetched */
143 private $warmupKeyMisses = 0;
144
145 /** @var float|null */
146 private $wallClockOverride;
147
148 /** Max time expected to pass between delete() and DB commit finishing */
149 const MAX_COMMIT_DELAY = 3;
150 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
151 const MAX_READ_LAG = 7;
152 /** Seconds to tombstone keys on delete() */
153 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
154
155 /** Seconds to keep dependency purge keys around */
156 const CHECK_KEY_TTL = self::TTL_YEAR;
157 /** Seconds to keep interim value keys for tombstoned keys around */
158 const INTERIM_KEY_TTL = 1;
159
160 /** Seconds to keep lock keys around */
161 const LOCK_TTL = 10;
162 /** Seconds to no-op key set() calls to avoid large blob I/O stampedes */
163 const COOLOFF_TTL = 1;
164 /** Default remaining TTL at which to consider pre-emptive regeneration */
165 const LOW_TTL = 30;
166 /** Max TTL to store keys when a data sourced is lagged */
167 const TTL_LAGGED = 30;
168
169 /** Never consider performing "popularity" refreshes until a key reaches this age */
170 const AGE_NEW = 60;
171 /** The time length of the "popularity" refresh window for hot keys */
172 const HOT_TTR = 900;
173 /** Hits/second for a refresh to be expected within the "popularity" window */
174 const HIT_RATE_HIGH = 1;
175 /** Seconds to ramp up to the "popularity" refresh chance after a key is no longer new */
176 const RAMPUP_TTL = 30;
177
178 /** Idiom for getWithSetCallback() meaning "do not store the callback result" */
179 const TTL_UNCACHEABLE = -1;
180 /** Idiom for getWithSetCallback() meaning "no regeneration mutex based on key hotness" */
181 const TSE_NONE = -1;
182 /** Idiom for set()/getWithSetCallback() meaning "no post-expiration persistence" */
183 const STALE_TTL_NONE = 0;
184 /** Idiom for set()/getWithSetCallback() meaning "no post-expiration grace period" */
185 const GRACE_TTL_NONE = 0;
186 /** Idiom for delete()/touchCheckKey() meaning "no hold-off period for cache writes" */
187 const HOLDOFF_NONE = 0;
188
189 /** Idiom for getWithSetCallback() meaning "no minimum required as-of timestamp" */
190 const MIN_TIMESTAMP_NONE = 0.0;
191 /** @var int One second into the UNIX timestamp epoch */
192 const EPOCH_UNIX_ONE_SECOND = 1.0;
193
194 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
195 const TINY_NEGATIVE = -0.000001;
196 /** Tiny positive float to use when using "minTime" to assert an inequality */
197 const TINY_POSTIVE = 0.000001;
198
199 /** Milliseconds of delay after get() where set() storms are a consideration with "lockTSE" */
200 const SET_DELAY_HIGH_MS = 50;
201 /** Min millisecond set() backoff for keys in hold-off (far less than INTERIM_KEY_TTL) */
202 const RECENT_SET_LOW_MS = 50;
203 /** Max millisecond set() backoff for keys in hold-off (far less than INTERIM_KEY_TTL) */
204 const RECENT_SET_HIGH_MS = 100;
205
206 /** @var int Seconds needed for value generation considered slow */
207 const GENERATION_SLOW_SEC = 3;
208
209 /** Parameter to get()/getMulti() to return extra information by reference */
210 const PASS_BY_REF = -1;
211
212 /** Cache format version number */
213 const VERSION = 1;
214
215 const FLD_FORMAT_VERSION = 0; // key to WAN cache version number
216 const FLD_VALUE = 1; // key to the cached value
217 const FLD_TTL = 2; // key to the original TTL
218 const FLD_TIME = 3; // key to the cache timestamp
219 const FLD_FLAGS = 4; // key to the flags bitfield (reserved number)
220 const FLD_VALUE_VERSION = 5; // key to collection cache version number
221 const FLD_GENERATION_TIME = 6; // key to how long it took to generate the value
222
223 const PURGE_TIME = 0; // key to the tombstone entry timestamp
224 const PURGE_HOLDOFF = 1; // key to the tombstone entry hold-off TTL
225
226 const VALUE_KEY_PREFIX = 'WANCache:v:';
227 const INTERIM_KEY_PREFIX = 'WANCache:i:';
228 const TIME_KEY_PREFIX = 'WANCache:t:';
229 const MUTEX_KEY_PREFIX = 'WANCache:m:';
230 const COOLOFF_KEY_PREFIX = 'WANCache:c:';
231
232 const PURGE_VAL_PREFIX = 'PURGED:';
233
234 const PC_PRIMARY = 'primary:1000'; // process cache name and max key count
235
236 /**
237 * @param array $params
238 * - cache : BagOStuff object for a persistent cache
239 * - logger : LoggerInterface object
240 * - stats : StatsdDataFactoryInterface object
241 * - asyncHandler : A function that takes a callback and runs it later. If supplied,
242 * whenever a preemptive refresh would be triggered in getWithSetCallback(), the
243 * current cache value is still used instead. However, the async-handler function
244 * receives a WAN cache callback that, when run, will execute the value generation
245 * callback supplied by the getWithSetCallback() caller. The result will be saved
246 * as normal. The handler is expected to call the WAN cache callback at an opportune
247 * time (e.g. HTTP post-send), though generally within a few 100ms. [optional]
248 * - region: the current physical region. This is required when using mcrouter as the
249 * backing store proxy. [optional]
250 * - cluster: name of the cache cluster used by this WAN cache. The name must be the
251 * same in all datacenters; the ("region","cluster") tuple is what distinguishes
252 * the counterpart cache clusters among all the datacenter. The contents of
253 * https://github.com/facebook/mcrouter/wiki/Config-Files give background on this.
254 * This is required when using mcrouter as the backing store proxy. [optional]
255 * - mcrouterAware: set as true if mcrouter is the backing store proxy and mcrouter
256 * is configured to interpret /<region>/<cluster>/ key prefixes as routes. This
257 * requires that "region" and "cluster" are both set above. [optional]
258 * - epoch: lowest UNIX timestamp a value/tombstone must have to be valid. [optional]
259 */
260 public function __construct( array $params ) {
261 $this->cache = $params['cache'];
262 $this->region = $params['region'] ?? 'main';
263 $this->cluster = $params['cluster'] ?? 'wan-main';
264 $this->mcrouterAware = !empty( $params['mcrouterAware'] );
265 $this->epoch = $params['epoch'] ?? self::EPOCH_UNIX_ONE_SECOND;
266
267 $this->setLogger( $params['logger'] ?? new NullLogger() );
268 $this->stats = $params['stats'] ?? new NullStatsdDataFactory();
269 $this->asyncHandler = $params['asyncHandler'] ?? null;
270 }
271
272 /**
273 * @param LoggerInterface $logger
274 */
275 public function setLogger( LoggerInterface $logger ) {
276 $this->logger = $logger;
277 }
278
279 /**
280 * Get an instance that wraps EmptyBagOStuff
281 *
282 * @return WANObjectCache
283 */
284 public static function newEmpty() {
285 return new static( [ 'cache' => new EmptyBagOStuff() ] );
286 }
287
288 /**
289 * Fetch the value of a key from cache
290 *
291 * If supplied, $curTTL is set to the remaining TTL (current time left):
292 * - a) INF; if $key exists, has no TTL, and is not invalidated by $checkKeys
293 * - b) float (>=0); if $key exists, has a TTL, and is not invalidated by $checkKeys
294 * - c) float (<0); if $key is tombstoned, stale, or existing but invalidated by $checkKeys
295 * - d) null; if $key does not exist and is not tombstoned
296 *
297 * If a key is tombstoned, $curTTL will reflect the time since delete().
298 *
299 * The timestamp of $key will be checked against the last-purge timestamp
300 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
301 * initialized to the current timestamp. If any of $checkKeys have a timestamp
302 * greater than that of $key, then $curTTL will reflect how long ago $key
303 * became invalid. Callers can use $curTTL to know when the value is stale.
304 * The $checkKeys parameter allow mass invalidations by updating a single key:
305 * - a) Each "check" key represents "last purged" of some source data
306 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
307 * - c) When the source data that "check" keys represent changes,
308 * the touchCheckKey() method is called on them
309 *
310 * Source data entities might exists in a DB that uses snapshot isolation
311 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
312 * isolation can largely be maintained by doing the following:
313 * - a) Calling delete() on entity change *and* creation, before DB commit
314 * - b) Keeping transaction duration shorter than the delete() hold-off TTL
315 * - c) Disabling interim key caching via useInterimHoldOffCaching() before get() calls
316 *
317 * However, pre-snapshot values might still be seen if an update was made
318 * in a remote datacenter but the purge from delete() didn't relay yet.
319 *
320 * Consider using getWithSetCallback() instead of get() and set() cycles.
321 * That method has cache slam avoiding features for hot/expensive keys.
322 *
323 * Pass $info as WANObjectCache::PASS_BY_REF to transform it into a cache key metadata map.
324 * This map includes the following metadata:
325 * - asOf: UNIX timestamp of the value or null if the key is nonexistant
326 * - tombAsOf: UNIX timestamp of the tombstone or null if the key is not tombstoned
327 * - lastCKPurge: UNIX timestamp of the highest check key or null if none provided
328 * - version: cached value version number or null if the key is nonexistant
329 *
330 * Otherwise, $info will transform into the cached value timestamp.
331 *
332 * @param string $key Cache key made from makeKey() or makeGlobalKey()
333 * @param mixed|null &$curTTL Approximate TTL left on the key if present/tombstoned [returned]
334 * @param array $checkKeys List of "check" keys
335 * @param mixed|null &$info Key info if WANObjectCache::PASS_BY_REF [returned]
336 * @return mixed Value of cache key or false on failure
337 */
338 final public function get(
339 $key, &$curTTL = null, array $checkKeys = [], &$info = null
340 ) {
341 $curTTLs = self::PASS_BY_REF;
342 $infoByKey = self::PASS_BY_REF;
343 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $infoByKey );
344 $curTTL = $curTTLs[$key] ?? null;
345 if ( $info === self::PASS_BY_REF ) {
346 $info = [
347 'asOf' => $infoByKey[$key]['asOf'] ?? null,
348 'tombAsOf' => $infoByKey[$key]['tombAsOf'] ?? null,
349 'lastCKPurge' => $infoByKey[$key]['lastCKPurge'] ?? null,
350 'version' => $infoByKey[$key]['version'] ?? null
351 ];
352 } else {
353 $info = $infoByKey[$key]['asOf'] ?? null; // b/c
354 }
355
356 return $values[$key] ?? false;
357 }
358
359 /**
360 * Fetch the value of several keys from cache
361 *
362 * Pass $info as WANObjectCache::PASS_BY_REF to transform it into a map of cache keys
363 * to cache key metadata maps, each having the same style as those of WANObjectCache::get().
364 * All the cache keys listed in $keys will have an entry.
365 *
366 * Othwerwise, $info will transform into a map of (cache key => cached value timestamp).
367 * Only the cache keys listed in $keys that exists or are tombstoned will have an entry.
368 *
369 * @see WANObjectCache::get()
370 *
371 * @param array $keys List of cache keys made from makeKey() or makeGlobalKey()
372 * @param mixed|null &$curTTLs Map of (key => TTL left) for existing/tombstoned keys [returned]
373 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
374 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
375 * @param mixed|null &$info Map of (key => info) if WANObjectCache::PASS_BY_REF [returned]
376 * @return array Map of (key => value) for keys that exist and are not tombstoned
377 */
378 final public function getMulti(
379 array $keys,
380 &$curTTLs = [],
381 array $checkKeys = [],
382 &$info = null
383 ) {
384 $result = [];
385 $curTTLs = [];
386 $infoByKey = [];
387
388 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
389 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
390
391 $checkKeysForAll = [];
392 $checkKeysByKey = [];
393 $checkKeysFlat = [];
394 foreach ( $checkKeys as $i => $checkKeyGroup ) {
395 $prefixed = self::prefixCacheKeys( (array)$checkKeyGroup, self::TIME_KEY_PREFIX );
396 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
397 // Are these check keys for a specific cache key, or for all keys being fetched?
398 if ( is_int( $i ) ) {
399 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
400 } else {
401 $checkKeysByKey[$i] = $prefixed;
402 }
403 }
404
405 // Fetch all of the raw values
406 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
407 if ( $this->warmupCache ) {
408 $wrappedValues = array_intersect_key( $this->warmupCache, array_flip( $keysGet ) );
409 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) ); // keys left to fetch
410 $this->warmupKeyMisses += count( $keysGet );
411 } else {
412 $wrappedValues = [];
413 }
414 if ( $keysGet ) {
415 $wrappedValues += $this->cache->getMulti( $keysGet );
416 }
417 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
418 $now = $this->getCurrentTime();
419
420 // Collect timestamps from all "check" keys
421 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
422 $purgeValuesByKey = [];
423 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
424 $purgeValuesByKey[$cacheKey] =
425 $this->processCheckKeys( $checks, $wrappedValues, $now );
426 }
427
428 // Get the main cache value for each key and validate them
429 foreach ( $valueKeys as $vKey ) {
430 $key = substr( $vKey, $vPrefixLen ); // unprefix
431 list( $value, $keyInfo ) = $this->unwrap( $wrappedValues[$vKey] ?? false, $now );
432 // Force dependent keys to be seen as stale for a while after purging
433 // to reduce race conditions involving stale data getting cached
434 $purgeValues = $purgeValuesForAll;
435 if ( isset( $purgeValuesByKey[$key] ) ) {
436 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
437 }
438
439 $lastCKPurge = null; // timestamp of the highest check key
440 foreach ( $purgeValues as $purge ) {
441 $lastCKPurge = max( $purge[self::PURGE_TIME], $lastCKPurge );
442 $safeTimestamp = $purge[self::PURGE_TIME] + $purge[self::PURGE_HOLDOFF];
443 if ( $value !== false && $safeTimestamp >= $keyInfo['asOf'] ) {
444 // How long ago this value was invalidated by *this* check key
445 $ago = min( $purge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
446 // How long ago this value was invalidated by *any* known check key
447 $keyInfo['curTTL'] = min( $keyInfo['curTTL'], $ago );
448 }
449 }
450 $keyInfo[ 'lastCKPurge'] = $lastCKPurge;
451
452 if ( $value !== false ) {
453 $result[$key] = $value;
454 }
455 if ( $keyInfo['curTTL'] !== null ) {
456 $curTTLs[$key] = $keyInfo['curTTL'];
457 }
458
459 $infoByKey[$key] = ( $info === self::PASS_BY_REF )
460 ? $keyInfo
461 : $keyInfo['asOf']; // b/c
462 }
463
464 $info = $infoByKey;
465
466 return $result;
467 }
468
469 /**
470 * @since 1.27
471 * @param array $timeKeys List of prefixed time check keys
472 * @param array $wrappedValues
473 * @param float $now
474 * @return array List of purge value arrays
475 */
476 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
477 $purgeValues = [];
478 foreach ( $timeKeys as $timeKey ) {
479 $purge = isset( $wrappedValues[$timeKey] )
480 ? $this->parsePurgeValue( $wrappedValues[$timeKey] )
481 : false;
482 if ( $purge === false ) {
483 // Key is not set or malformed; regenerate
484 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
485 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
486 $purge = $this->parsePurgeValue( $newVal );
487 }
488 $purgeValues[] = $purge;
489 }
490 return $purgeValues;
491 }
492
493 /**
494 * Set the value of a key in cache
495 *
496 * Simply calling this method when source data changes is not valid because
497 * the changes do not replicate to the other WAN sites. In that case, delete()
498 * should be used instead. This method is intended for use on cache misses.
499 *
500 * If the data was read from a snapshot-isolated transactions (e.g. the default
501 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
502 * - a) T1 starts
503 * - b) T2 updates a row, calls delete(), and commits
504 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
505 * - d) T1 reads the row and calls set() due to a cache miss
506 * - e) Stale value is stuck in cache
507 *
508 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
509 *
510 * Be aware that this does not update the process cache for getWithSetCallback()
511 * callers. Keys accessed via that method are not generally meant to also be set
512 * using this primitive method.
513 *
514 * Do not use this method on versioned keys accessed via getWithSetCallback().
515 *
516 * Example usage:
517 * @code
518 * $dbr = wfGetDB( DB_REPLICA );
519 * $setOpts = Database::getCacheSetOptions( $dbr );
520 * // Fetch the row from the DB
521 * $row = $dbr->selectRow( ... );
522 * $key = $cache->makeKey( 'building', $buildingId );
523 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
524 * @endcode
525 *
526 * @param string $key Cache key
527 * @param mixed $value
528 * @param int $ttl Seconds to live. Special values are:
529 * - WANObjectCache::TTL_INDEFINITE: Cache forever (default)
530 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
531 * @param array $opts Options map:
532 * - lag: Seconds of replica DB lag. Typically, this is either the replica DB lag
533 * before the data was read or, if applicable, the replica DB lag before
534 * the snapshot-isolated transaction the data was read from started.
535 * Use false to indicate that replication is not running.
536 * Default: 0 seconds
537 * - since: UNIX timestamp of the data in $value. Typically, this is either
538 * the current time the data was read or (if applicable) the time when
539 * the snapshot-isolated transaction the data was read from started.
540 * Default: 0 seconds
541 * - pending: Whether this data is possibly from an uncommitted write transaction.
542 * Generally, other threads should not see values from the future and
543 * they certainly should not see ones that ended up getting rolled back.
544 * Default: false
545 * - lockTSE: If excessive replication/snapshot lag is detected, then store the value
546 * with this TTL and flag it as stale. This is only useful if the reads for this key
547 * use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set
548 * then it will still add on to this TTL in the excessive lag scenario.
549 * Default: WANObjectCache::TSE_NONE
550 * - staleTTL: Seconds to keep the key around if it is stale. The get()/getMulti()
551 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
552 * will call the regeneration callback in such cases, passing in the old value
553 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
554 * on the old value's as-of time when it is verified as still being correct.
555 * Default: WANObjectCache::STALE_TTL_NONE
556 * - creating: Optimize for the case where the key does not already exist.
557 * Default: false
558 * - version: Integer version number signifiying the format of the value.
559 * Default: null
560 * - walltime: How long the value took to generate in seconds. Default: 0.0
561 * @note Options added in 1.28: staleTTL
562 * @note Options added in 1.33: creating
563 * @note Options added in 1.34: version, walltime
564 * @return bool Success
565 */
566 final public function set( $key, $value, $ttl = self::TTL_INDEFINITE, array $opts = [] ) {
567 $now = $this->getCurrentTime();
568 $lag = $opts['lag'] ?? 0;
569 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
570 $pending = $opts['pending'] ?? false;
571 $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
572 $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
573 $creating = $opts['creating'] ?? false;
574 $version = $opts['version'] ?? null;
575 $walltime = $opts['walltime'] ?? 0.0;
576
577 if ( $ttl < 0 ) {
578 return true;
579 }
580
581 // Do not cache potentially uncommitted data as it might get rolled back
582 if ( $pending ) {
583 $this->logger->info(
584 'Rejected set() for {cachekey} due to pending writes.',
585 [ 'cachekey' => $key ]
586 );
587
588 return true; // no-op the write for being unsafe
589 }
590
591 $logicalTTL = null; // logical TTL override
592 // Check if there's a risk of writing stale data after the purge tombstone expired
593 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
594 // Case A: any long-running transaction
595 if ( $age > self::MAX_READ_LAG ) {
596 if ( $lockTSE >= 0 ) {
597 // Store value as *almost* stale to avoid cache and mutex stampedes
598 $logicalTTL = self::TTL_SECOND;
599 $this->logger->info(
600 'Lowered set() TTL for {cachekey} due to snapshot lag.',
601 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
602 );
603 } else {
604 $this->logger->info(
605 'Rejected set() for {cachekey} due to snapshot lag.',
606 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
607 );
608
609 return true; // no-op the write for being unsafe
610 }
611 // Case B: high replication lag; lower TTL instead of ignoring all set()s
612 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
613 if ( $lockTSE >= 0 ) {
614 $logicalTTL = min( $ttl ?: INF, self::TTL_LAGGED );
615 } else {
616 $ttl = min( $ttl ?: INF, self::TTL_LAGGED );
617 }
618 $this->logger->warning(
619 'Lowered set() TTL for {cachekey} due to replication lag.',
620 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
621 );
622 // Case C: medium length request with medium replication lag
623 } elseif ( $lockTSE >= 0 ) {
624 // Store value as *almost* stale to avoid cache and mutex stampedes
625 $logicalTTL = self::TTL_SECOND;
626 $this->logger->info(
627 'Lowered set() TTL for {cachekey} due to high read lag.',
628 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
629 );
630 } else {
631 $this->logger->info(
632 'Rejected set() for {cachekey} due to high read lag.',
633 [ 'cachekey' => $key, 'lag' => $lag, 'age' => $age ]
634 );
635
636 return true; // no-op the write for being unsafe
637 }
638 }
639
640 // Wrap that value with time/TTL/version metadata
641 $wrapped = $this->wrap( $value, $logicalTTL ?: $ttl, $version, $now, $walltime );
642 $storeTTL = $ttl + $staleTTL;
643
644 if ( $creating ) {
645 $ok = $this->cache->add( self::VALUE_KEY_PREFIX . $key, $wrapped, $storeTTL );
646 } else {
647 $ok = $this->cache->merge(
648 self::VALUE_KEY_PREFIX . $key,
649 function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
650 // A string value means that it is a tombstone; do nothing in that case
651 return ( is_string( $cWrapped ) ) ? false : $wrapped;
652 },
653 $storeTTL,
654 1 // 1 attempt
655 );
656 }
657
658 return $ok;
659 }
660
661 /**
662 * Purge a key from all datacenters
663 *
664 * This should only be called when the underlying data (being cached)
665 * changes in a significant way. This deletes the key and starts a hold-off
666 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
667 * This is done to avoid the following race condition:
668 * - a) Some DB data changes and delete() is called on a corresponding key
669 * - b) A request refills the key with a stale value from a lagged DB
670 * - c) The stale value is stuck there until the key is expired/evicted
671 *
672 * This is implemented by storing a special "tombstone" value at the cache
673 * key that this class recognizes; get() calls will return false for the key
674 * and any set() calls will refuse to replace tombstone values at the key.
675 * For this to always avoid stale value writes, the following must hold:
676 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
677 * - b) If lag is higher, the DB will have gone into read-only mode already
678 *
679 * Note that set() can also be lag-aware and lower the TTL if it's high.
680 *
681 * Be aware that this does not clear the process cache. Even if it did, callbacks
682 * used by getWithSetCallback() might still return stale data in the case of either
683 * uncommitted or not-yet-replicated changes (callback generally use replica DBs).
684 *
685 * When using potentially long-running ACID transactions, a good pattern is
686 * to use a pre-commit hook to issue the delete. This means that immediately
687 * after commit, callers will see the tombstone in cache upon purge relay.
688 * It also avoids the following race condition:
689 * - a) T1 begins, changes a row, and calls delete()
690 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
691 * - c) T2 starts, reads the row and calls set() due to a cache miss
692 * - d) T1 finally commits
693 * - e) Stale value is stuck in cache
694 *
695 * Example usage:
696 * @code
697 * $dbw->startAtomic( __METHOD__ ); // start of request
698 * ... <execute some stuff> ...
699 * // Update the row in the DB
700 * $dbw->update( ... );
701 * $key = $cache->makeKey( 'homes', $homeId );
702 * // Purge the corresponding cache entry just before committing
703 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
704 * $cache->delete( $key );
705 * } );
706 * ... <execute some stuff> ...
707 * $dbw->endAtomic( __METHOD__ ); // end of request
708 * @endcode
709 *
710 * The $ttl parameter can be used when purging values that have not actually changed
711 * recently. For example, a cleanup script to purge cache entries does not really need
712 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
713 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
714 *
715 * If called twice on the same key, then the last hold-off TTL takes precedence. For
716 * idempotence, the $ttl should not vary for different delete() calls on the same key.
717 *
718 * @param string $key Cache key
719 * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
720 * @return bool True if the item was purged or not found, false on failure
721 */
722 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
723 if ( $ttl <= 0 ) {
724 // Publish the purge to all datacenters
725 $ok = $this->relayDelete( self::VALUE_KEY_PREFIX . $key );
726 } else {
727 // Publish the purge to all datacenters
728 $ok = $this->relayPurge( self::VALUE_KEY_PREFIX . $key, $ttl, self::HOLDOFF_NONE );
729 }
730
731 $kClass = $this->determineKeyClassForStats( $key );
732 $this->stats->increment( "wanobjectcache.$kClass.delete." . ( $ok ? 'ok' : 'error' ) );
733
734 return $ok;
735 }
736
737 /**
738 * Fetch the value of a timestamp "check" key
739 *
740 * The key will be *initialized* to the current time if not set,
741 * so only call this method if this behavior is actually desired
742 *
743 * The timestamp can be used to check whether a cached value is valid.
744 * Callers should not assume that this returns the same timestamp in
745 * all datacenters due to relay delays.
746 *
747 * The level of staleness can roughly be estimated from this key, but
748 * if the key was evicted from cache, such calculations may show the
749 * time since expiry as ~0 seconds.
750 *
751 * Note that "check" keys won't collide with other regular keys.
752 *
753 * @param string $key
754 * @return float UNIX timestamp
755 */
756 final public function getCheckKeyTime( $key ) {
757 return $this->getMultiCheckKeyTime( [ $key ] )[$key];
758 }
759
760 /**
761 * Fetch the values of each timestamp "check" key
762 *
763 * This works like getCheckKeyTime() except it takes a list of keys
764 * and returns a map of timestamps instead of just that of one key
765 *
766 * This might be useful if both:
767 * - a) a class of entities each depend on hundreds of other entities
768 * - b) these other entities are depended upon by millions of entities
769 *
770 * The later entities can each use a "check" key to invalidate their dependee entities.
771 * However, it is expensive for the former entities to verify against all of the relevant
772 * "check" keys during each getWithSetCallback() call. A less expensive approach is to do
773 * these verifications only after a "time-till-verify" (TTV) has passed. This is a middle
774 * ground between using blind TTLs and using constant verification. The adaptiveTTL() method
775 * can be used to dynamically adjust the TTV. Also, the initial TTV can make use of the
776 * last-modified times of the dependant entities (either from the DB or the "check" keys).
777 *
778 * Example usage:
779 * @code
780 * $value = $cache->getWithSetCallback(
781 * $cache->makeGlobalKey( 'wikibase-item', $id ),
782 * self::INITIAL_TTV, // initial time-till-verify
783 * function ( $oldValue, &$ttv, &$setOpts, $oldAsOf ) use ( $checkKeys, $cache ) {
784 * $now = microtime( true );
785 * // Use $oldValue if it passes max ultimate age and "check" key comparisons
786 * if ( $oldValue &&
787 * $oldAsOf > max( $cache->getMultiCheckKeyTime( $checkKeys ) ) &&
788 * ( $now - $oldValue['ctime'] ) <= self::MAX_CACHE_AGE
789 * ) {
790 * // Increase time-till-verify by 50% of last time to reduce overhead
791 * $ttv = $cache->adaptiveTTL( $oldAsOf, self::MAX_TTV, self::MIN_TTV, 1.5 );
792 * // Unlike $oldAsOf, "ctime" is the ultimate age of the cached data
793 * return $oldValue;
794 * }
795 *
796 * $mtimes = []; // dependency last-modified times; passed by reference
797 * $value = [ 'data' => $this->fetchEntityData( $mtimes ), 'ctime' => $now ];
798 * // Guess time-till-change among the dependencies, e.g. 1/(total change rate)
799 * $ttc = 1 / array_sum( array_map(
800 * function ( $mtime ) use ( $now ) {
801 * return 1 / ( $mtime ? ( $now - $mtime ) : 900 );
802 * },
803 * $mtimes
804 * ) );
805 * // The time-to-verify should not be overly pessimistic nor optimistic
806 * $ttv = min( max( $ttc, self::MIN_TTV ), self::MAX_TTV );
807 *
808 * return $value;
809 * },
810 * [ 'staleTTL' => $cache::TTL_DAY ] // keep around to verify and re-save
811 * );
812 * @endcode
813 *
814 * @see WANObjectCache::getCheckKeyTime()
815 * @see WANObjectCache::getWithSetCallback()
816 *
817 * @param array $keys
818 * @return float[] Map of (key => UNIX timestamp)
819 * @since 1.31
820 */
821 final public function getMultiCheckKeyTime( array $keys ) {
822 $rawKeys = [];
823 foreach ( $keys as $key ) {
824 $rawKeys[$key] = self::TIME_KEY_PREFIX . $key;
825 }
826
827 $rawValues = $this->cache->getMulti( $rawKeys );
828 $rawValues += array_fill_keys( $rawKeys, false );
829
830 $times = [];
831 foreach ( $rawKeys as $key => $rawKey ) {
832 $purge = $this->parsePurgeValue( $rawValues[$rawKey] );
833 if ( $purge !== false ) {
834 $time = $purge[self::PURGE_TIME];
835 } else {
836 // Casting assures identical floats for the next getCheckKeyTime() calls
837 $now = (string)$this->getCurrentTime();
838 $this->cache->add(
839 $rawKey,
840 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
841 self::CHECK_KEY_TTL
842 );
843 $time = (float)$now;
844 }
845
846 $times[$key] = $time;
847 }
848
849 return $times;
850 }
851
852 /**
853 * Purge a "check" key from all datacenters, invalidating keys that use it
854 *
855 * This should only be called when the underlying data (being cached)
856 * changes in a significant way, and it is impractical to call delete()
857 * on all keys that should be changed. When get() is called on those
858 * keys, the relevant "check" keys must be supplied for this to work.
859 *
860 * The "check" key essentially represents a last-modified time of an entity.
861 * When the key is touched, the timestamp will be updated to the current time.
862 * Keys using the "check" key via get(), getMulti(), or getWithSetCallback() will
863 * be invalidated. This approach is useful if many keys depend on a single entity.
864 *
865 * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the
866 * future by get*() methods in order to avoid race conditions where keys are updated
867 * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check"
868 * key, making it possible to know the timestamp of the last change to the corresponding
869 * entities in most cases. This might use more cache space than resetCheckKey().
870 *
871 * When a few important keys get a large number of hits, a high cache time is usually
872 * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate
873 * in such cases since the "time since expiry" cannot be inferred, causing any get()
874 * after the reset to treat the key as being "hot", resulting in more stale value usage.
875 *
876 * Note that "check" keys won't collide with other regular keys.
877 *
878 * @see WANObjectCache::get()
879 * @see WANObjectCache::getWithSetCallback()
880 * @see WANObjectCache::resetCheckKey()
881 *
882 * @param string $key Cache key
883 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
884 * @return bool True if the item was purged or not found, false on failure
885 */
886 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
887 // Publish the purge to all datacenters
888 $ok = $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
889
890 $kClass = $this->determineKeyClassForStats( $key );
891 $this->stats->increment( "wanobjectcache.$kClass.ck_touch." . ( $ok ? 'ok' : 'error' ) );
892
893 return $ok;
894 }
895
896 /**
897 * Delete a "check" key from all datacenters, invalidating keys that use it
898 *
899 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
900 * or getWithSetCallback() will be invalidated. The differences are:
901 * - a) The "check" key will be deleted from all caches and lazily
902 * re-initialized when accessed (rather than set everywhere)
903 * - b) Thus, dependent keys will be known to be stale, but not
904 * for how long (they are treated as "just" purged), which
905 * effects any lockTSE logic in getWithSetCallback()
906 * - c) Since "check" keys are initialized only on the server the key hashes
907 * to, any temporary ejection of that server will cause the value to be
908 * seen as purged as a new server will initialize the "check" key.
909 *
910 * The advantage here is that the "check" keys, which have high TTLs, will only
911 * be created when a get*() method actually uses that key. This is better when
912 * a large number of "check" keys are invalided in a short period of time.
913 *
914 * Note that "check" keys won't collide with other regular keys.
915 *
916 * @see WANObjectCache::get()
917 * @see WANObjectCache::getWithSetCallback()
918 * @see WANObjectCache::touchCheckKey()
919 *
920 * @param string $key Cache key
921 * @return bool True if the item was purged or not found, false on failure
922 */
923 final public function resetCheckKey( $key ) {
924 // Publish the purge to all datacenters
925 $ok = $this->relayDelete( self::TIME_KEY_PREFIX . $key );
926
927 $kClass = $this->determineKeyClassForStats( $key );
928 $this->stats->increment( "wanobjectcache.$kClass.ck_reset." . ( $ok ? 'ok' : 'error' ) );
929
930 return $ok;
931 }
932
933 /**
934 * Method to fetch/regenerate cache keys
935 *
936 * On cache miss, the key will be set to the callback result via set()
937 * (unless the callback returns false) and that result will be returned.
938 * The arguments supplied to the callback are:
939 * - $oldValue : current cache value or false if not present
940 * - &$ttl : a reference to the TTL which can be altered
941 * - &$setOpts : a reference to options for set() which can be altered
942 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present (since 1.28)
943 *
944 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
945 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
946 * value, but it can be used to maintain "most recent X" values that come from time or
947 * sequence based source data, provided that the "as of" id/time is tracked. Note that
948 * preemptive regeneration and $checkKeys can result in a non-false current value.
949 *
950 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
951 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
952 * regeneration will automatically be triggered using the callback.
953 *
954 * The $ttl argument and "hotTTR" option (in $opts) use time-dependant randomization
955 * to avoid stampedes. Keys that are slow to regenerate and either heavily used
956 * or subject to explicit (unpredictable) purges, may need additional mechanisms.
957 * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts).
958 * If explicit purges are needed, also:
959 * - a) Pass $key into $checkKeys
960 * - b) Use touchCheckKey( $key ) instead of delete( $key )
961 *
962 * Example usage (typical key):
963 * @code
964 * $catInfo = $cache->getWithSetCallback(
965 * // Key to store the cached value under
966 * $cache->makeKey( 'cat-attributes', $catId ),
967 * // Time-to-live (in seconds)
968 * $cache::TTL_MINUTE,
969 * // Function that derives the new key value
970 * function ( $oldValue, &$ttl, array &$setOpts ) {
971 * $dbr = wfGetDB( DB_REPLICA );
972 * // Account for any snapshot/replica DB lag
973 * $setOpts += Database::getCacheSetOptions( $dbr );
974 *
975 * return $dbr->selectRow( ... );
976 * }
977 * );
978 * @endcode
979 *
980 * Example usage (key that is expensive and hot):
981 * @code
982 * $catConfig = $cache->getWithSetCallback(
983 * // Key to store the cached value under
984 * $cache->makeKey( 'site-cat-config' ),
985 * // Time-to-live (in seconds)
986 * $cache::TTL_DAY,
987 * // Function that derives the new key value
988 * function ( $oldValue, &$ttl, array &$setOpts ) {
989 * $dbr = wfGetDB( DB_REPLICA );
990 * // Account for any snapshot/replica DB lag
991 * $setOpts += Database::getCacheSetOptions( $dbr );
992 *
993 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
994 * },
995 * [
996 * // Calling touchCheckKey() on this key invalidates the cache
997 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
998 * // Try to only let one datacenter thread manage cache updates at a time
999 * 'lockTSE' => 30,
1000 * // Avoid querying cache servers multiple times in a web request
1001 * 'pcTTL' => $cache::TTL_PROC_LONG
1002 * ]
1003 * );
1004 * @endcode
1005 *
1006 * Example usage (key with dynamic dependencies):
1007 * @code
1008 * $catState = $cache->getWithSetCallback(
1009 * // Key to store the cached value under
1010 * $cache->makeKey( 'cat-state', $cat->getId() ),
1011 * // Time-to-live (seconds)
1012 * $cache::TTL_HOUR,
1013 * // Function that derives the new key value
1014 * function ( $oldValue, &$ttl, array &$setOpts ) {
1015 * // Determine new value from the DB
1016 * $dbr = wfGetDB( DB_REPLICA );
1017 * // Account for any snapshot/replica DB lag
1018 * $setOpts += Database::getCacheSetOptions( $dbr );
1019 *
1020 * return CatState::newFromResults( $dbr->select( ... ) );
1021 * },
1022 * [
1023 * // The "check" keys that represent things the value depends on;
1024 * // Calling touchCheckKey() on any of them invalidates the cache
1025 * 'checkKeys' => [
1026 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
1027 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
1028 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
1029 * ]
1030 * ]
1031 * );
1032 * @endcode
1033 *
1034 * Example usage (key that is expensive with too many DB dependencies for "check keys"):
1035 * @code
1036 * $catToys = $cache->getWithSetCallback(
1037 * // Key to store the cached value under
1038 * $cache->makeKey( 'cat-toys', $catId ),
1039 * // Time-to-live (seconds)
1040 * $cache::TTL_HOUR,
1041 * // Function that derives the new key value
1042 * function ( $oldValue, &$ttl, array &$setOpts ) {
1043 * // Determine new value from the DB
1044 * $dbr = wfGetDB( DB_REPLICA );
1045 * // Account for any snapshot/replica DB lag
1046 * $setOpts += Database::getCacheSetOptions( $dbr );
1047 *
1048 * return CatToys::newFromResults( $dbr->select( ... ) );
1049 * },
1050 * [
1051 * // Get the highest timestamp of any of the cat's toys
1052 * 'touchedCallback' => function ( $value ) use ( $catId ) {
1053 * $dbr = wfGetDB( DB_REPLICA );
1054 * $ts = $dbr->selectField( 'cat_toys', 'MAX(ct_touched)', ... );
1055 *
1056 * return wfTimestampOrNull( TS_UNIX, $ts );
1057 * },
1058 * // Avoid DB queries for repeated access
1059 * 'pcTTL' => $cache::TTL_PROC_SHORT
1060 * ]
1061 * );
1062 * @endcode
1063 *
1064 * Example usage (hot key holding most recent 100 events):
1065 * @code
1066 * $lastCatActions = $cache->getWithSetCallback(
1067 * // Key to store the cached value under
1068 * $cache->makeKey( 'cat-last-actions', 100 ),
1069 * // Time-to-live (in seconds)
1070 * 10,
1071 * // Function that derives the new key value
1072 * function ( $oldValue, &$ttl, array &$setOpts ) {
1073 * $dbr = wfGetDB( DB_REPLICA );
1074 * // Account for any snapshot/replica DB lag
1075 * $setOpts += Database::getCacheSetOptions( $dbr );
1076 *
1077 * // Start off with the last cached list
1078 * $list = $oldValue ?: [];
1079 * // Fetch the last 100 relevant rows in descending order;
1080 * // only fetch rows newer than $list[0] to reduce scanning
1081 * $rows = iterator_to_array( $dbr->select( ... ) );
1082 * // Merge them and get the new "last 100" rows
1083 * return array_slice( array_merge( $new, $list ), 0, 100 );
1084 * },
1085 * [
1086 * // Try to only let one datacenter thread manage cache updates at a time
1087 * 'lockTSE' => 30,
1088 * // Use a magic value when no cache value is ready rather than stampeding
1089 * 'busyValue' => 'computing'
1090 * ]
1091 * );
1092 * @endcode
1093 *
1094 * Example usage (key holding an LRU subkey:value map; this can avoid flooding cache with
1095 * keys for an unlimited set of (constraint,situation) pairs, thereby avoiding elevated
1096 * cache evictions and wasted memory):
1097 * @code
1098 * $catSituationTolerabilityCache = $this->cache->getWithSetCallback(
1099 * // Group by constraint ID/hash, cat family ID/hash, or something else useful
1100 * $this->cache->makeKey( 'cat-situation-tolerability-checks', $groupKey ),
1101 * WANObjectCache::TTL_DAY, // rarely used groups should fade away
1102 * // The $scenarioKey format is $constraintId:<ID/hash of $situation>
1103 * function ( $cacheMap ) use ( $scenarioKey, $constraintId, $situation ) {
1104 * $lruCache = MapCacheLRU::newFromArray( $cacheMap ?: [], self::CACHE_SIZE );
1105 * $result = $lruCache->get( $scenarioKey ); // triggers LRU bump if present
1106 * if ( $result === null || $this->isScenarioResultExpired( $result ) ) {
1107 * $result = $this->checkScenarioTolerability( $constraintId, $situation );
1108 * $lruCache->set( $scenarioKey, $result, 3 / 8 );
1109 * }
1110 * // Save the new LRU cache map and reset the map's TTL
1111 * return $lruCache->toArray();
1112 * },
1113 * [
1114 * // Once map is > 1 sec old, consider refreshing
1115 * 'ageNew' => 1,
1116 * // Update within 5 seconds after "ageNew" given a 1hz cache check rate
1117 * 'hotTTR' => 5,
1118 * // Avoid querying cache servers multiple times in a request; this also means
1119 * // that a request can only alter the value of any given constraint key once
1120 * 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1121 * ]
1122 * );
1123 * $tolerability = isset( $catSituationTolerabilityCache[$scenarioKey] )
1124 * ? $catSituationTolerabilityCache[$scenarioKey]
1125 * : $this->checkScenarioTolerability( $constraintId, $situation );
1126 * @endcode
1127 *
1128 * @see WANObjectCache::get()
1129 * @see WANObjectCache::set()
1130 *
1131 * @param string $key Cache key made from makeKey() or makeGlobalKey()
1132 * @param int $ttl Seconds to live for key updates. Special values are:
1133 * - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
1134 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
1135 * @param callable $callback Value generation function
1136 * @param array $opts Options map:
1137 * - checkKeys: List of "check" keys. The key at $key will be seen as stale when either
1138 * touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This
1139 * is useful if thousands or millions of keys depend on the same entity. The entity can
1140 * simply have its "check" key updated whenever the entity is modified.
1141 * Default: [].
1142 * - graceTTL: If the key is invalidated (by "checkKeys"/"touchedCallback") less than this
1143 * many seconds ago, consider reusing the stale value. The odds of a refresh becomes
1144 * more likely over time, becoming certain once the grace period is reached. This can
1145 * reduce traffic spikes when millions of keys are compared to the same "check" key and
1146 * touchCheckKey() or resetCheckKey() is called on that "check" key. This option is not
1147 * useful for avoiding traffic spikes in the case of the key simply expiring on account
1148 * of its TTL (use "lowTTL" instead).
1149 * Default: WANObjectCache::GRACE_TTL_NONE.
1150 * - lockTSE: If the key is tombstoned or invalidated (by "checkKeys"/"touchedCallback")
1151 * less than this many seconds ago, try to have a single thread handle cache regeneration
1152 * at any given time. Other threads will use stale values if possible. If, on miss,
1153 * the time since expiration is low, the assumption is that the key is hot and that a
1154 * stampede is worth avoiding. Note that if the key falls out of cache then concurrent
1155 * threads will all run the callback on cache miss until the value is saved in cache.
1156 * The only stampede protection in that case is from duplicate cache sets when the
1157 * callback takes longer than WANObjectCache::SET_DELAY_HIGH_MS milliseconds; consider
1158 * using "busyValue" if such stampedes are a problem. Note that the higher "lockTSE" is
1159 * set, the higher the worst-case staleness of returned values can be. Also note that
1160 * this option does not by itself handle the case of the key simply expiring on account
1161 * of its TTL, so make sure that "lowTTL" is not disabled when using this option. Avoid
1162 * combining this option with delete() as it can always cause a stampede due to their
1163 * being no stale value available until after a thread completes the callback.
1164 * Use WANObjectCache::TSE_NONE to disable this logic.
1165 * Default: WANObjectCache::TSE_NONE.
1166 * - busyValue: If no value exists and another thread is currently regenerating it, use this
1167 * as a fallback value (or a callback to generate such a value). This assures that cache
1168 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
1169 * against cache regeneration becoming very slow for some reason (greater than the TTL).
1170 * Default: null.
1171 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
1172 * network I/O when a key is read several times. This will not cache when the callback
1173 * returns false, however. Note that any purges will not be seen while process cached;
1174 * since the callback should use replica DBs and they may be lagged or have snapshot
1175 * isolation anyway, this should not typically matter.
1176 * Default: WANObjectCache::TTL_UNCACHEABLE.
1177 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
1178 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
1179 * large values, small yet numerous values, or some values with a high cost of eviction.
1180 * It is generally preferable to use a class constant when setting this value.
1181 * This has no effect unless pcTTL is used.
1182 * Default: WANObjectCache::PC_PRIMARY.
1183 * - version: Integer version number. This lets callers make breaking changes to the format
1184 * of cached values without causing problems for sites that use non-instantaneous code
1185 * deployments. Old and new code will recognize incompatible versions and purges from
1186 * both old and new code will been seen by each other. When this method encounters an
1187 * incompatibly versioned value at the provided key, a "variant key" will be used for
1188 * reading from and saving to cache. The variant key is specific to the key and version
1189 * number provided to this method. If the variant key value is older than that of the
1190 * provided key, or the provided key is non-existant, then the variant key will be seen
1191 * as non-existant. Therefore, delete() calls invalidate the provided key's variant keys.
1192 * The "checkKeys" and "touchedCallback" options still apply to variant keys as usual.
1193 * Avoid storing class objects, as this reduces compatibility (due to serialization).
1194 * Default: null.
1195 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
1196 * This is useful if the source of a key is suspected of having possibly changed
1197 * recently, and the caller wants any such changes to be reflected.
1198 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
1199 * - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per
1200 * second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this
1201 * TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old.
1202 * This uses randomization to avoid triggering cache stampedes. The TTR is useful at
1203 * reducing the impact of missed cache purges, since the effect of a heavily referenced
1204 * key being stale is worse than that of a rarely referenced key. Unlike simply lowering
1205 * $ttl, seldomly used keys are largely unaffected by this option, which makes it
1206 * possible to have a high hit rate for the "long-tail" of less-used keys.
1207 * Default: WANObjectCache::HOT_TTR.
1208 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
1209 * than this. It becomes more likely over time, becoming certain once the key is expired.
1210 * This helps avoid cache stampedes that might be triggered due to the key expiring.
1211 * Default: WANObjectCache::LOW_TTL.
1212 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
1213 * Default: WANObjectCache::AGE_NEW.
1214 * - staleTTL: Seconds to keep the key around if it is stale. This means that on cache
1215 * miss the callback may get $oldValue/$oldAsOf values for keys that have already been
1216 * expired for this specified time. This is useful if adaptiveTTL() is used on the old
1217 * value's as-of time when it is verified as still being correct.
1218 * Default: WANObjectCache::STALE_TTL_NONE
1219 * - touchedCallback: A callback that takes the current value and returns a UNIX timestamp
1220 * indicating the last time a dynamic dependency changed. Null can be returned if there
1221 * are no relevant dependency changes to check. This can be used to check against things
1222 * like last-modified times of files or DB timestamp fields. This should generally not be
1223 * used for small and easily queried values in a DB if the callback itself ends up doing
1224 * a similarly expensive DB query to check a timestamp. Usages of this option makes the
1225 * most sense for values that are moderately to highly expensive to regenerate and easy
1226 * to query for dependency timestamps. The use of "pcTTL" reduces timestamp queries.
1227 * Default: null.
1228 * @return mixed Value found or written to the key
1229 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
1230 * @note Options added in 1.31: staleTTL, graceTTL
1231 * @note Options added in 1.33: touchedCallback
1232 * @note Callable type hints are not used to avoid class-autoloading
1233 */
1234 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
1235 $version = $opts['version'] ?? null;
1236 $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
1237
1238 // Use the process cache if requested as long as no outer cache callback is running.
1239 // Nested callback process cache use is not lag-safe with regard to HOLDOFF_TTL since
1240 // process cached values are more lagged than persistent ones as they are not purged.
1241 if ( $pcTTL >= 0 && $this->callbackDepth == 0 ) {
1242 $pCache = $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY );
1243 $cached = $pCache->get( $this->getProcessCacheKey( $key, $version ), INF, false );
1244 if ( $cached !== false ) {
1245 return $cached;
1246 }
1247 } else {
1248 $pCache = null;
1249 }
1250
1251 $res = $this->fetchOrRegenerate( $key, $ttl, $callback, $opts );
1252 list( $value, $valueVersion, $curAsOf ) = $res;
1253 if ( $valueVersion !== $version ) {
1254 // Current value has a different version; use the variant key for this version.
1255 // Regenerate the variant value if it is not newer than the main value at $key
1256 // so that purges to the main key propagate to the variant value.
1257 list( $value ) = $this->fetchOrRegenerate(
1258 $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), $version ),
1259 $ttl,
1260 $callback,
1261 [ 'version' => null, 'minAsOf' => $curAsOf ] + $opts
1262 );
1263 }
1264
1265 // Update the process cache if enabled
1266 if ( $pCache && $value !== false ) {
1267 $pCache->set( $this->getProcessCacheKey( $key, $version ), $value );
1268 }
1269
1270 return $value;
1271 }
1272
1273 /**
1274 * Do the actual I/O for getWithSetCallback() when needed
1275 *
1276 * @see WANObjectCache::getWithSetCallback()
1277 *
1278 * @param string $key
1279 * @param int $ttl
1280 * @param callable $callback
1281 * @param array $opts Options map for getWithSetCallback()
1282 * @return array Ordered list of the following:
1283 * - Cached or regenerated value
1284 * - Cached or regenerated value version number or null if not versioned
1285 * - Timestamp of the cached value or null if there is no value
1286 * @note Callable type hints are not used to avoid class-autoloading
1287 */
1288 private function fetchOrRegenerate( $key, $ttl, $callback, array $opts ) {
1289 $checkKeys = $opts['checkKeys'] ?? [];
1290 $graceTTL = $opts['graceTTL'] ?? self::GRACE_TTL_NONE;
1291 $minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
1292 $hotTTR = $opts['hotTTR'] ?? self::HOT_TTR;
1293 $lowTTL = $opts['lowTTL'] ?? min( self::LOW_TTL, $ttl );
1294 $ageNew = $opts['ageNew'] ?? self::AGE_NEW;
1295 $touchedCb = $opts['touchedCallback'] ?? null;
1296 $initialTime = $this->getCurrentTime();
1297
1298 $kClass = $this->determineKeyClassForStats( $key );
1299
1300 // Get the current key value and its metadata
1301 $curTTL = self::PASS_BY_REF;
1302 $curInfo = self::PASS_BY_REF; /** @var array $curInfo */
1303 $curValue = $this->get( $key, $curTTL, $checkKeys, $curInfo );
1304 // Apply any $touchedCb invalidation timestamp to get the "last purge timestamp"
1305 list( $curTTL, $LPT ) = $this->resolveCTL( $curValue, $curTTL, $curInfo, $touchedCb );
1306 // Use the cached value if it exists and is not due for synchronous regeneration
1307 if (
1308 $this->isValid( $curValue, $curInfo['asOf'], $minAsOf ) &&
1309 $this->isAliveOrInGracePeriod( $curTTL, $graceTTL )
1310 ) {
1311 $preemptiveRefresh = (
1312 $this->worthRefreshExpiring( $curTTL, $lowTTL ) ||
1313 $this->worthRefreshPopular( $curInfo['asOf'], $ageNew, $hotTTR, $initialTime )
1314 );
1315 if ( !$preemptiveRefresh ) {
1316 $this->stats->increment( "wanobjectcache.$kClass.hit.good" );
1317
1318 return [ $curValue, $curInfo['version'], $curInfo['asOf'] ];
1319 } elseif ( $this->scheduleAsyncRefresh( $key, $ttl, $callback, $opts ) ) {
1320 $this->stats->increment( "wanobjectcache.$kClass.hit.refresh" );
1321
1322 return [ $curValue, $curInfo['version'], $curInfo['asOf'] ];
1323 }
1324 }
1325
1326 // Determine if there is stale or volatile cached value that is still usable
1327 $isKeyTombstoned = ( $curInfo['tombAsOf'] !== null );
1328 if ( $isKeyTombstoned ) {
1329 // Key is write-holed; use the (volatile) interim key as an alternative
1330 list( $possValue, $possInfo ) = $this->getInterimValue( $key, $minAsOf );
1331 // Update the "last purge time" since the $touchedCb timestamp depends on $value
1332 $LPT = $this->resolveTouched( $possValue, $LPT, $touchedCb );
1333 } else {
1334 $possValue = $curValue;
1335 $possInfo = $curInfo;
1336 }
1337
1338 // Avoid overhead from callback runs, regeneration locks, and cache sets during
1339 // hold-off periods for the key by reusing very recently generated cached values
1340 if (
1341 $this->isValid( $possValue, $possInfo['asOf'], $minAsOf, $LPT ) &&
1342 $this->isVolatileValueAgeNegligible( $initialTime - $possInfo['asOf'] )
1343 ) {
1344 $this->stats->increment( "wanobjectcache.$kClass.hit.volatile" );
1345
1346 return [ $possValue, $possInfo['version'], $curInfo['asOf'] ];
1347 }
1348
1349 $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
1350 $busyValue = $opts['busyValue'] ?? null;
1351 $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
1352 $version = $opts['version'] ?? null;
1353
1354 // Determine whether one thread per datacenter should handle regeneration at a time
1355 $useRegenerationLock =
1356 // Note that since tombstones no-op set(), $lockTSE and $curTTL cannot be used to
1357 // deduce the key hotness because |$curTTL| will always keep increasing until the
1358 // tombstone expires or is overwritten by a new tombstone. Also, even if $lockTSE
1359 // is not set, constant regeneration of a key for the tombstone lifetime might be
1360 // very expensive. Assume tombstoned keys are possibly hot in order to reduce
1361 // the risk of high regeneration load after the delete() method is called.
1362 $isKeyTombstoned ||
1363 // Assume a key is hot if requested soon ($lockTSE seconds) after invalidation.
1364 // This avoids stampedes when timestamps from $checkKeys/$touchedCb bump.
1365 ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE ) ||
1366 // Assume a key is hot if there is no value and a busy fallback is given.
1367 // This avoids stampedes on eviction or preemptive regeneration taking too long.
1368 ( $busyValue !== null && $possValue === false );
1369
1370 // If a regeneration lock is required, threads that do not get the lock will use any
1371 // available stale or volatile value. If there is none, then the cheap/placeholder
1372 // value from $busyValue will be used if provided; failing that, all threads will try
1373 // to regenerate the value and ignore the lock.
1374 if ( $useRegenerationLock ) {
1375 $hasLock = $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL );
1376 if ( !$hasLock ) {
1377 if ( $this->isValid( $possValue, $possInfo['asOf'], $minAsOf ) ) {
1378 $this->stats->increment( "wanobjectcache.$kClass.hit.stale" );
1379
1380 return [ $possValue, $possInfo['version'], $curInfo['asOf'] ];
1381 } elseif ( $busyValue !== null ) {
1382 $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1383 $this->stats->increment( "wanobjectcache.$kClass.$miss.busy" );
1384
1385 return [
1386 is_callable( $busyValue ) ? $busyValue() : $busyValue,
1387 $version,
1388 $curInfo['asOf']
1389 ];
1390 }
1391 }
1392 } else {
1393 $hasLock = false;
1394 }
1395
1396 // Generate the new value given any prior value with a matching version
1397 $setOpts = [];
1398 $preCallbackTime = $this->getCurrentTime();
1399 ++$this->callbackDepth;
1400 try {
1401 $value = $callback(
1402 ( $curInfo['version'] === $version ) ? $curValue : false,
1403 $ttl,
1404 $setOpts,
1405 ( $curInfo['version'] === $version ) ? $curInfo['asOf'] : null
1406 );
1407 } finally {
1408 --$this->callbackDepth;
1409 }
1410 $postCallbackTime = $this->getCurrentTime();
1411
1412 // How long it took to fetch, validate, and generate the value
1413 $elapsed = max( $postCallbackTime - $initialTime, 0.0 );
1414
1415 // Attempt to save the newly generated value if applicable
1416 if (
1417 // Callback yielded a cacheable value
1418 ( $value !== false && $ttl >= 0 ) &&
1419 // Current thread was not raced out of a regeneration lock or key is tombstoned
1420 ( !$useRegenerationLock || $hasLock || $isKeyTombstoned ) &&
1421 // Key does not appear to be undergoing a set() stampede
1422 $this->checkAndSetCooloff( $key, $kClass, $elapsed, $lockTSE, $hasLock )
1423 ) {
1424 // How long it took to generate the value
1425 $walltime = max( $postCallbackTime - $preCallbackTime, 0.0 );
1426 // If the key is write-holed then use the (volatile) interim key as an alternative
1427 if ( $isKeyTombstoned ) {
1428 $this->setInterimValue( $key, $value, $lockTSE, $version, $walltime );
1429 } else {
1430 $finalSetOpts = [
1431 'since' => $setOpts['since'] ?? $preCallbackTime,
1432 'version' => $version,
1433 'staleTTL' => $staleTTL,
1434 'lockTSE' => $lockTSE, // informs lag vs performance trade-offs
1435 'creating' => ( $curValue === false ), // optimization
1436 'walltime' => $walltime
1437 ] + $setOpts;
1438 $this->set( $key, $value, $ttl, $finalSetOpts );
1439 }
1440 }
1441
1442 if ( $hasLock ) {
1443 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, (int)$initialTime - 60 );
1444 }
1445
1446 $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1447 $this->stats->increment( "wanobjectcache.$kClass.$miss.compute" );
1448
1449 return [ $value, $version, $curInfo['asOf'] ];
1450 }
1451
1452 /**
1453 * @param float $age Age of volatile/interim key in seconds
1454 * @return bool Whether the age of a volatile value is negligible
1455 */
1456 private function isVolatileValueAgeNegligible( $age ) {
1457 return ( $age < mt_rand( self::RECENT_SET_LOW_MS, self::RECENT_SET_HIGH_MS ) / 1e3 );
1458 }
1459
1460 /**
1461 * @param string $key
1462 * @param string $kClass
1463 * @param float $elapsed Seconds spent regenerating the value
1464 * @param float $lockTSE
1465 * @param bool $hasLock
1466 * @return bool Whether it is OK to proceed with a key set operation
1467 */
1468 private function checkAndSetCooloff( $key, $kClass, $elapsed, $lockTSE, $hasLock ) {
1469 $this->stats->timing( "wanobjectcache.$kClass.regen_set_delay", 1e3 * $elapsed );
1470
1471 // If $lockTSE is set, the lock was bypassed because there was no stale/interim value,
1472 // and $elapsed indicates that regeration is slow, then there is a risk of set()
1473 // stampedes with large blobs. With a typical scale-out infrastructure, CPU and query
1474 // load from $callback invocations is distributed among appservers and replica DBs,
1475 // but cache operations for a given key route to a single cache server (e.g. striped
1476 // consistent hashing).
1477 if ( $lockTSE < 0 || $hasLock ) {
1478 return true; // either not a priori hot or thread has the lock
1479 } elseif ( $elapsed <= self::SET_DELAY_HIGH_MS * 1e3 ) {
1480 return true; // not enough time for threads to pile up
1481 }
1482
1483 $this->cache->clearLastError();
1484 if (
1485 !$this->cache->add( self::COOLOFF_KEY_PREFIX . $key, 1, self::COOLOFF_TTL ) &&
1486 // Don't treat failures due to I/O errors as the key being in cooloff
1487 $this->cache->getLastError() === BagOStuff::ERR_NONE
1488 ) {
1489 $this->stats->increment( "wanobjectcache.$kClass.cooloff_bounce" );
1490
1491 return false;
1492 }
1493
1494 return true;
1495 }
1496
1497 /**
1498 * @param mixed $value
1499 * @param float|null $curTTL
1500 * @param array $curInfo
1501 * @param callable|null $touchedCallback
1502 * @return array (current time left or null, UNIX timestamp of last purge or null)
1503 * @note Callable type hints are not used to avoid class-autoloading
1504 */
1505 private function resolveCTL( $value, $curTTL, $curInfo, $touchedCallback ) {
1506 if ( $touchedCallback === null || $value === false ) {
1507 return [ $curTTL, max( $curInfo['tombAsOf'], $curInfo['lastCKPurge'] ) ];
1508 }
1509
1510 $touched = $touchedCallback( $value );
1511 if ( $touched !== null && $touched >= $curInfo['asOf'] ) {
1512 $curTTL = min( $curTTL, self::TINY_NEGATIVE, $curInfo['asOf'] - $touched );
1513 }
1514
1515 return [ $curTTL, max( $curInfo['tombAsOf'], $curInfo['lastCKPurge'], $touched ) ];
1516 }
1517
1518 /**
1519 * @param mixed $value
1520 * @param float|null $lastPurge
1521 * @param callable|null $touchedCallback
1522 * @return float|null UNIX timestamp of last purge or null
1523 * @note Callable type hints are not used to avoid class-autoloading
1524 */
1525 private function resolveTouched( $value, $lastPurge, $touchedCallback ) {
1526 return ( $touchedCallback === null || $value === false )
1527 ? $lastPurge // nothing to derive the "touched timestamp" from
1528 : max( $touchedCallback( $value ), $lastPurge );
1529 }
1530
1531 /**
1532 * @param string $key
1533 * @param float $minAsOf Minimum acceptable "as of" timestamp
1534 * @return array (cached value or false, cache key metadata map)
1535 */
1536 private function getInterimValue( $key, $minAsOf ) {
1537 $now = $this->getCurrentTime();
1538
1539 if ( $this->useInterimHoldOffCaching ) {
1540 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
1541
1542 list( $value, $keyInfo ) = $this->unwrap( $wrapped, $now );
1543 if ( $this->isValid( $value, $keyInfo['asOf'], $minAsOf ) ) {
1544 return [ $value, $keyInfo ];
1545 }
1546 }
1547
1548 return $this->unwrap( false, $now );
1549 }
1550
1551 /**
1552 * @param string $key
1553 * @param mixed $value
1554 * @param int $ttl
1555 * @param int|null $version Value version number
1556 * @param float $walltime How long it took to generate the value in seconds
1557 */
1558 private function setInterimValue( $key, $value, $ttl, $version, $walltime ) {
1559 $ttl = max( self::INTERIM_KEY_TTL, (int)$ttl );
1560
1561 $wrapped = $this->wrap( $value, $ttl, $version, $this->getCurrentTime(), $walltime );
1562 $this->cache->merge(
1563 self::INTERIM_KEY_PREFIX . $key,
1564 function () use ( $wrapped ) {
1565 return $wrapped;
1566 },
1567 $ttl,
1568 1
1569 );
1570 }
1571
1572 /**
1573 * Method to fetch multiple cache keys at once with regeneration
1574 *
1575 * This works the same as getWithSetCallback() except:
1576 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1577 * - b) The $callback argument expects a callback taking the following arguments:
1578 * - $id: ID of an entity to query
1579 * - $oldValue : the prior cache value or false if none was present
1580 * - &$ttl : a reference to the new value TTL in seconds
1581 * - &$setOpts : a reference to options for set() which can be altered
1582 * - $oldAsOf : generation UNIX timestamp of $oldValue or null if not present
1583 * Aside from the additional $id argument, the other arguments function the same
1584 * way they do in getWithSetCallback().
1585 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1586 *
1587 * @see WANObjectCache::getWithSetCallback()
1588 * @see WANObjectCache::getMultiWithUnionSetCallback()
1589 *
1590 * Example usage:
1591 * @code
1592 * $rows = $cache->getMultiWithSetCallback(
1593 * // Map of cache keys to entity IDs
1594 * $cache->makeMultiKeys(
1595 * $this->fileVersionIds(),
1596 * function ( $id, WANObjectCache $cache ) {
1597 * return $cache->makeKey( 'file-version', $id );
1598 * }
1599 * ),
1600 * // Time-to-live (in seconds)
1601 * $cache::TTL_DAY,
1602 * // Function that derives the new key value
1603 * function ( $id, $oldValue, &$ttl, array &$setOpts ) {
1604 * $dbr = wfGetDB( DB_REPLICA );
1605 * // Account for any snapshot/replica DB lag
1606 * $setOpts += Database::getCacheSetOptions( $dbr );
1607 *
1608 * // Load the row for this file
1609 * $queryInfo = File::getQueryInfo();
1610 * $row = $dbr->selectRow(
1611 * $queryInfo['tables'],
1612 * $queryInfo['fields'],
1613 * [ 'id' => $id ],
1614 * __METHOD__,
1615 * [],
1616 * $queryInfo['joins']
1617 * );
1618 *
1619 * return $row ? (array)$row : false;
1620 * },
1621 * [
1622 * // Process cache for 30 seconds
1623 * 'pcTTL' => 30,
1624 * // Use a dedicated 500 item cache (initialized on-the-fly)
1625 * 'pcGroup' => 'file-versions:500'
1626 * ]
1627 * );
1628 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1629 * @endcode
1630 *
1631 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1632 * @param int $ttl Seconds to live for key updates
1633 * @param callable $callback Callback the yields entity regeneration callbacks
1634 * @param array $opts Options map
1635 * @return array Map of (cache key => value) in the same order as $keyedIds
1636 * @since 1.28
1637 */
1638 final public function getMultiWithSetCallback(
1639 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1640 ) {
1641 $valueKeys = array_keys( $keyedIds->getArrayCopy() );
1642
1643 // Load required keys into process cache in one go
1644 $this->warmupCache = $this->getRawKeysForWarmup(
1645 $this->getNonProcessCachedKeys( $valueKeys, $opts ),
1646 $opts['checkKeys'] ?? []
1647 );
1648 $this->warmupKeyMisses = 0;
1649
1650 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1651 $id = null; // current entity ID
1652 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf ) use ( $callback, &$id ) {
1653 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1654 };
1655
1656 $values = [];
1657 foreach ( $keyedIds as $key => $id ) { // preserve order
1658 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1659 }
1660
1661 $this->warmupCache = [];
1662
1663 return $values;
1664 }
1665
1666 /**
1667 * Method to fetch/regenerate multiple cache keys at once
1668 *
1669 * This works the same as getWithSetCallback() except:
1670 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
1671 * - b) The $callback argument expects a callback returning a map of (ID => new value)
1672 * for all entity IDs in $ids and it takes the following arguments:
1673 * - $ids: a list of entity IDs that require cache regeneration
1674 * - &$ttls: a reference to the (entity ID => new TTL) map
1675 * - &$setOpts: a reference to options for set() which can be altered
1676 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
1677 * - d) The "lockTSE" and "busyValue" options are ignored
1678 *
1679 * @see WANObjectCache::getWithSetCallback()
1680 * @see WANObjectCache::getMultiWithSetCallback()
1681 *
1682 * Example usage:
1683 * @code
1684 * $rows = $cache->getMultiWithUnionSetCallback(
1685 * // Map of cache keys to entity IDs
1686 * $cache->makeMultiKeys(
1687 * $this->fileVersionIds(),
1688 * function ( $id, WANObjectCache $cache ) {
1689 * return $cache->makeKey( 'file-version', $id );
1690 * }
1691 * ),
1692 * // Time-to-live (in seconds)
1693 * $cache::TTL_DAY,
1694 * // Function that derives the new key value
1695 * function ( array $ids, array &$ttls, array &$setOpts ) {
1696 * $dbr = wfGetDB( DB_REPLICA );
1697 * // Account for any snapshot/replica DB lag
1698 * $setOpts += Database::getCacheSetOptions( $dbr );
1699 *
1700 * // Load the rows for these files
1701 * $rows = [];
1702 * $queryInfo = File::getQueryInfo();
1703 * $res = $dbr->select(
1704 * $queryInfo['tables'],
1705 * $queryInfo['fields'],
1706 * [ 'id' => $ids ],
1707 * __METHOD__,
1708 * [],
1709 * $queryInfo['joins']
1710 * );
1711 * foreach ( $res as $row ) {
1712 * $rows[$row->id] = $row;
1713 * $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
1714 * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
1715 * }
1716 *
1717 * return $rows;
1718 * },
1719 * ]
1720 * );
1721 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
1722 * @endcode
1723 *
1724 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
1725 * @param int $ttl Seconds to live for key updates
1726 * @param callable $callback Callback the yields entity regeneration callbacks
1727 * @param array $opts Options map
1728 * @return array Map of (cache key => value) in the same order as $keyedIds
1729 * @since 1.30
1730 */
1731 final public function getMultiWithUnionSetCallback(
1732 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1733 ) {
1734 $idsByValueKey = $keyedIds->getArrayCopy();
1735 $valueKeys = array_keys( $idsByValueKey );
1736 $checkKeys = $opts['checkKeys'] ?? [];
1737 unset( $opts['lockTSE'] ); // incompatible
1738 unset( $opts['busyValue'] ); // incompatible
1739
1740 // Load required keys into process cache in one go
1741 $keysGet = $this->getNonProcessCachedKeys( $valueKeys, $opts );
1742 $this->warmupCache = $this->getRawKeysForWarmup( $keysGet, $checkKeys );
1743 $this->warmupKeyMisses = 0;
1744
1745 // IDs of entities known to be in need of regeneration
1746 $idsRegen = [];
1747
1748 // Find out which keys are missing/deleted/stale
1749 $curTTLs = [];
1750 $asOfs = [];
1751 $curByKey = $this->getMulti( $keysGet, $curTTLs, $checkKeys, $asOfs );
1752 foreach ( $keysGet as $key ) {
1753 if ( !array_key_exists( $key, $curByKey ) || $curTTLs[$key] < 0 ) {
1754 $idsRegen[] = $idsByValueKey[$key];
1755 }
1756 }
1757
1758 // Run the callback to populate the regeneration value map for all required IDs
1759 $newSetOpts = [];
1760 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
1761 $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
1762
1763 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1764 $id = null; // current entity ID
1765 $func = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1766 use ( $callback, &$id, $newValsById, $newTTLsById, $newSetOpts )
1767 {
1768 if ( array_key_exists( $id, $newValsById ) ) {
1769 // Value was already regerated as expected, so use the value in $newValsById
1770 $newValue = $newValsById[$id];
1771 $ttl = $newTTLsById[$id];
1772 $setOpts = $newSetOpts;
1773 } else {
1774 // Pre-emptive/popularity refresh and version mismatch cases are not detected
1775 // above and thus $newValsById has no entry. Run $callback on this single entity.
1776 $ttls = [ $id => $ttl ];
1777 $newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
1778 $ttl = $ttls[$id];
1779 }
1780
1781 return $newValue;
1782 };
1783
1784 // Run the cache-aside logic using warmupCache instead of persistent cache queries
1785 $values = [];
1786 foreach ( $idsByValueKey as $key => $id ) { // preserve order
1787 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1788 }
1789
1790 $this->warmupCache = [];
1791
1792 return $values;
1793 }
1794
1795 /**
1796 * Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1797 *
1798 * This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids
1799 * broadcasting in mcrouter setups and also avoids races with new tombstones.
1800 *
1801 * @param string $key Cache key
1802 * @param int $purgeTimestamp UNIX timestamp of purge
1803 * @param bool &$isStale Whether the key is stale
1804 * @return bool Success
1805 * @since 1.28
1806 */
1807 final public function reap( $key, $purgeTimestamp, &$isStale = false ) {
1808 $minAsOf = $purgeTimestamp + self::HOLDOFF_TTL;
1809 $wrapped = $this->cache->get( self::VALUE_KEY_PREFIX . $key );
1810 if ( is_array( $wrapped ) && $wrapped[self::FLD_TIME] < $minAsOf ) {
1811 $isStale = true;
1812 $this->logger->warning( "Reaping stale value key '$key'." );
1813 $ttlReap = self::HOLDOFF_TTL; // avoids races with tombstone creation
1814 $ok = $this->cache->changeTTL( self::VALUE_KEY_PREFIX . $key, $ttlReap );
1815 if ( !$ok ) {
1816 $this->logger->error( "Could not complete reap of key '$key'." );
1817 }
1818
1819 return $ok;
1820 }
1821
1822 $isStale = false;
1823
1824 return true;
1825 }
1826
1827 /**
1828 * Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp
1829 *
1830 * @param string $key Cache key
1831 * @param int $purgeTimestamp UNIX timestamp of purge
1832 * @param bool &$isStale Whether the key is stale
1833 * @return bool Success
1834 * @since 1.28
1835 */
1836 final public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
1837 $purge = $this->parsePurgeValue( $this->cache->get( self::TIME_KEY_PREFIX . $key ) );
1838 if ( $purge && $purge[self::PURGE_TIME] < $purgeTimestamp ) {
1839 $isStale = true;
1840 $this->logger->warning( "Reaping stale check key '$key'." );
1841 $ok = $this->cache->changeTTL( self::TIME_KEY_PREFIX . $key, self::TTL_SECOND );
1842 if ( !$ok ) {
1843 $this->logger->error( "Could not complete reap of check key '$key'." );
1844 }
1845
1846 return $ok;
1847 }
1848
1849 $isStale = false;
1850
1851 return false;
1852 }
1853
1854 /**
1855 * @see BagOStuff::makeKey()
1856 * @param string $class Key class
1857 * @param string|null $component [optional] Key component (starting with a key collection name)
1858 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1859 * @since 1.27
1860 */
1861 public function makeKey( $class, $component = null ) {
1862 return $this->cache->makeKey( ...func_get_args() );
1863 }
1864
1865 /**
1866 * @see BagOStuff::makeGlobalKey()
1867 * @param string $class Key class
1868 * @param string|null $component [optional] Key component (starting with a key collection name)
1869 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
1870 * @since 1.27
1871 */
1872 public function makeGlobalKey( $class, $component = null ) {
1873 return $this->cache->makeGlobalKey( ...func_get_args() );
1874 }
1875
1876 /**
1877 * @param array $entities List of entity IDs
1878 * @param callable $keyFunc Callback yielding a key from (entity ID, this WANObjectCache)
1879 * @return ArrayIterator Iterator yielding (cache key => entity ID) in $entities order
1880 * @since 1.28
1881 */
1882 final public function makeMultiKeys( array $entities, callable $keyFunc ) {
1883 $map = [];
1884 foreach ( $entities as $entity ) {
1885 $map[$keyFunc( $entity, $this )] = $entity;
1886 }
1887
1888 return new ArrayIterator( $map );
1889 }
1890
1891 /**
1892 * Get the "last error" registered; clearLastError() should be called manually
1893 * @return int ERR_* class constant for the "last error" registry
1894 */
1895 final public function getLastError() {
1896 $code = $this->cache->getLastError();
1897 switch ( $code ) {
1898 case BagOStuff::ERR_NONE:
1899 return self::ERR_NONE;
1900 case BagOStuff::ERR_NO_RESPONSE:
1901 return self::ERR_NO_RESPONSE;
1902 case BagOStuff::ERR_UNREACHABLE:
1903 return self::ERR_UNREACHABLE;
1904 default:
1905 return self::ERR_UNEXPECTED;
1906 }
1907 }
1908
1909 /**
1910 * Clear the "last error" registry
1911 */
1912 final public function clearLastError() {
1913 $this->cache->clearLastError();
1914 }
1915
1916 /**
1917 * Clear the in-process caches; useful for testing
1918 *
1919 * @since 1.27
1920 */
1921 public function clearProcessCache() {
1922 $this->processCaches = [];
1923 }
1924
1925 /**
1926 * Enable or disable the use of brief caching for tombstoned keys
1927 *
1928 * When a key is purged via delete(), there normally is a period where caching
1929 * is hold-off limited to an extremely short time. This method will disable that
1930 * caching, forcing the callback to run for any of:
1931 * - WANObjectCache::getWithSetCallback()
1932 * - WANObjectCache::getMultiWithSetCallback()
1933 * - WANObjectCache::getMultiWithUnionSetCallback()
1934 *
1935 * This is useful when both:
1936 * - a) the database used by the callback is known to be up-to-date enough
1937 * for some particular purpose (e.g. replica DB has applied transaction X)
1938 * - b) the caller needs to exploit that fact, and therefore needs to avoid the
1939 * use of inherently volatile and possibly stale interim keys
1940 *
1941 * @see WANObjectCache::delete()
1942 * @param bool $enabled Whether to enable interim caching
1943 * @since 1.31
1944 */
1945 final public function useInterimHoldOffCaching( $enabled ) {
1946 $this->useInterimHoldOffCaching = $enabled;
1947 }
1948
1949 /**
1950 * @param int $flag ATTR_* class constant
1951 * @return int QOS_* class constant
1952 * @since 1.28
1953 */
1954 public function getQoS( $flag ) {
1955 return $this->cache->getQoS( $flag );
1956 }
1957
1958 /**
1959 * Get a TTL that is higher for objects that have not changed recently
1960 *
1961 * This is useful for keys that get explicit purges and DB or purge relay
1962 * lag is a potential concern (especially how it interacts with CDN cache)
1963 *
1964 * Example usage:
1965 * @code
1966 * // Last-modified time of page
1967 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1968 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1969 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1970 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1971 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1972 * @endcode
1973 *
1974 * Another use case is when there are no applicable "last modified" fields in the DB,
1975 * and there are too many dependencies for explicit purges to be viable, and the rate of
1976 * change to relevant content is unstable, and it is highly valued to have the cached value
1977 * be as up-to-date as possible.
1978 *
1979 * Example usage:
1980 * @code
1981 * $query = "<some complex query>";
1982 * $idListFromComplexQuery = $cache->getWithSetCallback(
1983 * $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
1984 * GraphQueryClass::STARTING_TTL,
1985 * function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
1986 * $gdb = $this->getReplicaGraphDbConnection();
1987 * // Account for any snapshot/replica DB lag
1988 * $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
1989 *
1990 * $newList = iterator_to_array( $gdb->query( $query ) );
1991 * sort( $newList, SORT_NUMERIC ); // normalize
1992 *
1993 * $minTTL = GraphQueryClass::MIN_TTL;
1994 * $maxTTL = GraphQueryClass::MAX_TTL;
1995 * if ( $oldValue !== false ) {
1996 * // Note that $oldAsOf is the last time this callback ran
1997 * $ttl = ( $newList === $oldValue )
1998 * // No change: cache for 150% of the age of $oldValue
1999 * ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
2000 * // Changed: cache for 50% of the age of $oldValue
2001 * : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
2002 * }
2003 *
2004 * return $newList;
2005 * },
2006 * [
2007 * // Keep stale values around for doing comparisons for TTL calculations.
2008 * // High values improve long-tail keys hit-rates, though might waste space.
2009 * 'staleTTL' => GraphQueryClass::GRACE_TTL
2010 * ]
2011 * );
2012 * @endcode
2013 *
2014 * @param int|float $mtime UNIX timestamp
2015 * @param int $maxTTL Maximum TTL (seconds)
2016 * @param int $minTTL Minimum TTL (seconds); Default: 30
2017 * @param float $factor Value in the range (0,1); Default: .2
2018 * @return int Adaptive TTL
2019 * @since 1.28
2020 */
2021 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
2022 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
2023 $mtime = (int)$mtime; // handle fractional seconds and string integers
2024 }
2025
2026 if ( !is_int( $mtime ) || $mtime <= 0 ) {
2027 return $minTTL; // no last-modified time provided
2028 }
2029
2030 $age = $this->getCurrentTime() - $mtime;
2031
2032 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
2033 }
2034
2035 /**
2036 * @return int Number of warmup key cache misses last round
2037 * @since 1.30
2038 */
2039 final public function getWarmupKeyMisses() {
2040 return $this->warmupKeyMisses;
2041 }
2042
2043 /**
2044 * Do the actual async bus purge of a key
2045 *
2046 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
2047 *
2048 * @param string $key Cache key
2049 * @param int $ttl Seconds to keep the tombstone around
2050 * @param int $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
2051 * @return bool Success
2052 */
2053 protected function relayPurge( $key, $ttl, $holdoff ) {
2054 if ( $this->mcrouterAware ) {
2055 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
2056 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
2057 $ok = $this->cache->set(
2058 "/*/{$this->cluster}/{$key}",
2059 $this->makePurgeValue( $this->getCurrentTime(), self::HOLDOFF_NONE ),
2060 $ttl
2061 );
2062 } else {
2063 // This handles the mcrouter and the single-DC case
2064 $ok = $this->cache->set(
2065 $key,
2066 $this->makePurgeValue( $this->getCurrentTime(), self::HOLDOFF_NONE ),
2067 $ttl
2068 );
2069 }
2070
2071 return $ok;
2072 }
2073
2074 /**
2075 * Do the actual async bus delete of a key
2076 *
2077 * @param string $key Cache key
2078 * @return bool Success
2079 */
2080 protected function relayDelete( $key ) {
2081 if ( $this->mcrouterAware ) {
2082 // See https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup
2083 // Wildcards select all matching routes, e.g. the WAN cluster on all DCs
2084 $ok = $this->cache->delete( "/*/{$this->cluster}/{$key}" );
2085 } else {
2086 // Some other proxy handles broadcasting or there is only one datacenter
2087 $ok = $this->cache->delete( $key );
2088 }
2089
2090 return $ok;
2091 }
2092
2093 /**
2094 * @param string $key
2095 * @param int $ttl Seconds to live
2096 * @param callable $callback
2097 * @param array $opts
2098 * @return bool Success
2099 * @note Callable type hints are not used to avoid class-autoloading
2100 */
2101 private function scheduleAsyncRefresh( $key, $ttl, $callback, $opts ) {
2102 if ( !$this->asyncHandler ) {
2103 return false;
2104 }
2105 // Update the cache value later, such during post-send of an HTTP request
2106 $func = $this->asyncHandler;
2107 $func( function () use ( $key, $ttl, $callback, $opts ) {
2108 $opts['minAsOf'] = INF; // force a refresh
2109 $this->fetchOrRegenerate( $key, $ttl, $callback, $opts );
2110 } );
2111
2112 return true;
2113 }
2114
2115 /**
2116 * Check if a key is fresh or in the grace window and thus due for randomized reuse
2117 *
2118 * If $curTTL > 0 (e.g. not expired) this returns true. Otherwise, the chance of returning
2119 * true decrease steadily from 100% to 0% as the |$curTTL| moves from 0 to $graceTTL seconds.
2120 * This handles widely varying levels of cache access traffic.
2121 *
2122 * If $curTTL <= -$graceTTL (e.g. already expired), then this returns false.
2123 *
2124 * @param float $curTTL Approximate TTL left on the key if present
2125 * @param int $graceTTL Consider using stale values if $curTTL is greater than this
2126 * @return bool
2127 */
2128 private function isAliveOrInGracePeriod( $curTTL, $graceTTL ) {
2129 if ( $curTTL > 0 ) {
2130 return true;
2131 } elseif ( $graceTTL <= 0 ) {
2132 return false;
2133 }
2134
2135 $ageStale = abs( $curTTL ); // seconds of staleness
2136 $curGTTL = ( $graceTTL - $ageStale ); // current grace-time-to-live
2137 if ( $curGTTL <= 0 ) {
2138 return false; // already out of grace period
2139 }
2140
2141 // Chance of using a stale value is the complement of the chance of refreshing it
2142 return !$this->worthRefreshExpiring( $curGTTL, $graceTTL );
2143 }
2144
2145 /**
2146 * Check if a key is nearing expiration and thus due for randomized regeneration
2147 *
2148 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance of returning true
2149 * increases steadily from 0% to 100% as the $curTTL moves from $lowTTL to 0 seconds.
2150 * This handles widely varying levels of cache access traffic.
2151 *
2152 * If $curTTL <= 0 (e.g. already expired), then this returns false.
2153 *
2154 * @param float $curTTL Approximate TTL left on the key if present
2155 * @param float $lowTTL Consider a refresh when $curTTL is less than this
2156 * @return bool
2157 */
2158 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
2159 if ( $lowTTL <= 0 ) {
2160 return false;
2161 } elseif ( $curTTL >= $lowTTL ) {
2162 return false;
2163 } elseif ( $curTTL <= 0 ) {
2164 return false;
2165 }
2166
2167 $chance = ( 1 - $curTTL / $lowTTL );
2168
2169 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
2170 }
2171
2172 /**
2173 * Check if a key is due for randomized regeneration due to its popularity
2174 *
2175 * This is used so that popular keys can preemptively refresh themselves for higher
2176 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
2177 * in cache with their high nominal TTL. This means popular keys keep good consistency,
2178 * whether the data changes frequently or not, and long-tail keys get to stay in cache
2179 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
2180 *
2181 * @param float $asOf UNIX timestamp of the value
2182 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
2183 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
2184 * @param float $now The current UNIX timestamp
2185 * @return bool
2186 */
2187 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
2188 if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
2189 return false;
2190 }
2191
2192 $age = $now - $asOf;
2193 $timeOld = $age - $ageNew;
2194 if ( $timeOld <= 0 ) {
2195 return false;
2196 }
2197
2198 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
2199 // Note that the "expected # of refreshes" for the ramp-up time range is half of what it
2200 // would be if P(refresh) was at its full value during that time range.
2201 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
2202 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
2203 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
2204 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
2205 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
2206
2207 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
2208 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
2209
2210 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
2211 }
2212
2213 /**
2214 * Check if $value is not false, versioned (if needed), and not older than $minTime (if set)
2215 *
2216 * @param array|bool $value
2217 * @param float $asOf The time $value was generated
2218 * @param float $minAsOf Minimum acceptable "as of" timestamp
2219 * @param float|null $purgeTime The last time the value was invalidated
2220 * @return bool
2221 */
2222 protected function isValid( $value, $asOf, $minAsOf, $purgeTime = null ) {
2223 // Avoid reading any key not generated after the latest delete() or touch
2224 $safeMinAsOf = max( $minAsOf, $purgeTime + self::TINY_POSTIVE );
2225
2226 if ( $value === false ) {
2227 return false;
2228 } elseif ( $safeMinAsOf > 0 && $asOf < $minAsOf ) {
2229 return false;
2230 }
2231
2232 return true;
2233 }
2234
2235 /**
2236 * @param mixed $value
2237 * @param int $ttl Seconds to live or zero for "indefinite"
2238 * @param int|null $version Value version number or null if not versioned
2239 * @param float $now Unix Current timestamp just before calling set()
2240 * @param float $walltime How long it took to generate the value in seconds
2241 * @return array
2242 */
2243 private function wrap( $value, $ttl, $version, $now, $walltime ) {
2244 // Returns keys in ascending integer order for PHP7 array packing:
2245 // https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html
2246 $wrapped = [
2247 self::FLD_FORMAT_VERSION => self::VERSION,
2248 self::FLD_VALUE => $value,
2249 self::FLD_TTL => $ttl,
2250 self::FLD_TIME => $now
2251 ];
2252 if ( $version !== null ) {
2253 $wrapped[self::FLD_VALUE_VERSION] = $version;
2254 }
2255 if ( $walltime >= self::GENERATION_SLOW_SEC ) {
2256 $wrapped[self::FLD_GENERATION_TIME] = $walltime;
2257 }
2258
2259 return $wrapped;
2260 }
2261
2262 /**
2263 * @param array|string|bool $wrapped The entry at a cache key
2264 * @param float $now Unix Current timestamp (preferrably pre-query)
2265 * @return array (value or false if absent/tombstoned/malformed, value metadata map).
2266 * The cache key metadata includes the following metadata:
2267 * - asOf: UNIX timestamp of the value or null if there is no value
2268 * - curTTL: remaining time-to-live (negative if tombstoned) or null if there is no value
2269 * - version: value version number or null if the if there is no value
2270 * - tombAsOf: UNIX timestamp of the tombstone or null if there is no tombstone
2271 */
2272 private function unwrap( $wrapped, $now ) {
2273 $value = false;
2274 $info = [ 'asOf' => null, 'curTTL' => null, 'version' => null, 'tombAsOf' => null ];
2275
2276 if ( is_array( $wrapped ) ) {
2277 // Entry expected to be a cached value; validate it
2278 if (
2279 ( $wrapped[self::FLD_FORMAT_VERSION] ?? null ) === self::VERSION &&
2280 $wrapped[self::FLD_TIME] >= $this->epoch
2281 ) {
2282 if ( $wrapped[self::FLD_TTL] > 0 ) {
2283 // Get the approximate time left on the key
2284 $age = $now - $wrapped[self::FLD_TIME];
2285 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
2286 } else {
2287 // Key had no TTL, so the time left is unbounded
2288 $curTTL = INF;
2289 }
2290 $value = $wrapped[self::FLD_VALUE];
2291 $info['version'] = $wrapped[self::FLD_VALUE_VERSION] ?? null;
2292 $info['asOf'] = $wrapped[self::FLD_TIME];
2293 $info['curTTL'] = $curTTL;
2294 }
2295 } else {
2296 // Entry expected to be a tombstone; parse it
2297 $purge = $this->parsePurgeValue( $wrapped );
2298 if ( $purge !== false ) {
2299 // Tombstoned keys should always have a negative current $ttl
2300 $info['curTTL'] = min( $purge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
2301 $info['tombAsOf'] = $purge[self::PURGE_TIME];
2302 }
2303 }
2304
2305 return [ $value, $info ];
2306 }
2307
2308 /**
2309 * @param array $keys
2310 * @param string $prefix
2311 * @return string[]
2312 */
2313 protected static function prefixCacheKeys( array $keys, $prefix ) {
2314 $res = [];
2315 foreach ( $keys as $key ) {
2316 $res[] = $prefix . $key;
2317 }
2318
2319 return $res;
2320 }
2321
2322 /**
2323 * @param string $key String of the format <scope>:<class>[:<class or variable>]...
2324 * @return string A collection name to describe this class of key
2325 */
2326 private function determineKeyClassForStats( $key ) {
2327 $parts = explode( ':', $key, 3 );
2328
2329 return $parts[1] ?? $parts[0]; // sanity
2330 }
2331
2332 /**
2333 * @param string|array|bool $value Possible string of the form "PURGED:<timestamp>:<holdoff>"
2334 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
2335 * or false if value isn't a valid purge value
2336 */
2337 private function parsePurgeValue( $value ) {
2338 if ( !is_string( $value ) ) {
2339 return false;
2340 }
2341
2342 $segments = explode( ':', $value, 3 );
2343 if ( !isset( $segments[0] ) || !isset( $segments[1] )
2344 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
2345 ) {
2346 return false;
2347 }
2348
2349 if ( !isset( $segments[2] ) ) {
2350 // Back-compat with old purge values without holdoff
2351 $segments[2] = self::HOLDOFF_TTL;
2352 }
2353
2354 if ( $segments[1] < $this->epoch ) {
2355 // Values this old are ignored
2356 return false;
2357 }
2358
2359 return [
2360 self::PURGE_TIME => (float)$segments[1],
2361 self::PURGE_HOLDOFF => (int)$segments[2],
2362 ];
2363 }
2364
2365 /**
2366 * @param float $timestamp
2367 * @param int $holdoff In seconds
2368 * @return string Wrapped purge value
2369 */
2370 private function makePurgeValue( $timestamp, $holdoff ) {
2371 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
2372 }
2373
2374 /**
2375 * @param string $group
2376 * @return MapCacheLRU
2377 */
2378 private function getProcessCache( $group ) {
2379 if ( !isset( $this->processCaches[$group] ) ) {
2380 list( , $size ) = explode( ':', $group );
2381 $this->processCaches[$group] = new MapCacheLRU( (int)$size );
2382 }
2383
2384 return $this->processCaches[$group];
2385 }
2386
2387 /**
2388 * @param string $key
2389 * @param int $version
2390 * @return string
2391 */
2392 private function getProcessCacheKey( $key, $version ) {
2393 return $key . ' ' . (int)$version;
2394 }
2395
2396 /**
2397 * @param array $keys
2398 * @param array $opts
2399 * @return string[] List of keys
2400 */
2401 private function getNonProcessCachedKeys( array $keys, array $opts ) {
2402 $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
2403
2404 $keysFound = [];
2405 if ( $pcTTL > 0 && $this->callbackDepth == 0 ) {
2406 $version = $opts['version'] ?? null;
2407 $pCache = $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY );
2408 foreach ( $keys as $key ) {
2409 if ( $pCache->has( $this->getProcessCacheKey( $key, $version ), $pcTTL ) ) {
2410 $keysFound[] = $key;
2411 }
2412 }
2413 }
2414
2415 return array_diff( $keys, $keysFound );
2416 }
2417
2418 /**
2419 * @param array $keys
2420 * @param array $checkKeys
2421 * @return array Map of (cache key => mixed)
2422 */
2423 private function getRawKeysForWarmup( array $keys, array $checkKeys ) {
2424 if ( !$keys ) {
2425 return [];
2426 }
2427
2428 $keysWarmUp = [];
2429 // Get all the value keys to fetch...
2430 foreach ( $keys as $key ) {
2431 $keysWarmUp[] = self::VALUE_KEY_PREFIX . $key;
2432 }
2433 // Get all the check keys to fetch...
2434 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
2435 if ( is_int( $i ) ) {
2436 // Single check key that applies to all value keys
2437 $keysWarmUp[] = self::TIME_KEY_PREFIX . $checkKeyOrKeys;
2438 } else {
2439 // List of check keys that apply to value key $i
2440 $keysWarmUp = array_merge(
2441 $keysWarmUp,
2442 self::prefixCacheKeys( $checkKeyOrKeys, self::TIME_KEY_PREFIX )
2443 );
2444 }
2445 }
2446
2447 $warmupCache = $this->cache->getMulti( $keysWarmUp );
2448 $warmupCache += array_fill_keys( $keysWarmUp, false );
2449
2450 return $warmupCache;
2451 }
2452
2453 /**
2454 * @return float UNIX timestamp
2455 * @codeCoverageIgnore
2456 */
2457 protected function getCurrentTime() {
2458 if ( $this->wallClockOverride ) {
2459 return $this->wallClockOverride;
2460 }
2461
2462 $clockTime = (float)time(); // call this first
2463 // microtime() uses an initial gettimeofday() call added to usage clocks.
2464 // This can severely drift from time() and the microtime() value of other threads
2465 // due to undercounting of the amount of time elapsed. Instead of seeing the current
2466 // time as being in the past, use the value of time(). This avoids setting cache values
2467 // that will immediately be seen as expired and possibly cause stampedes.
2468 return max( microtime( true ), $clockTime );
2469 }
2470
2471 /**
2472 * @param float|null &$time Mock UNIX timestamp for testing
2473 * @codeCoverageIgnore
2474 */
2475 public function setMockTime( &$time ) {
2476 $this->wallClockOverride =& $time;
2477 $this->cache->setMockTime( $time );
2478 }
2479 }