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