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