Merge ".mailmap: Correct two contributor names"
[mediawiki.git] / includes / libs / objectcache / WANObjectCache.php
blobe2854a26c5de0184bad01a97ea168a3963c301de
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.
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.
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
18 * @file
21 namespace Wikimedia\ObjectCache;
23 use ArrayIterator;
24 use Closure;
25 use Exception;
26 use MapCacheLRU;
27 use Psr\Log\LoggerAwareInterface;
28 use Psr\Log\LoggerInterface;
29 use Psr\Log\NullLogger;
30 use RuntimeException;
31 use UnexpectedValueException;
32 use Wikimedia\LightweightObjectStore\ExpirationAwareness;
33 use Wikimedia\Stats\IBufferingStatsdDataFactory;
34 use Wikimedia\Stats\StatsFactory;
36 /**
37 * Multi-datacenter aware caching interface
39 * ### Using WANObjectCache
41 * %WANObjectCache (known as **WANCache**, pronounced whan-cache) improves performance
42 * by reducing database load, increasing web server capacity (fewer repeated computations) and
43 * providing faster access to data. The data cached here follows a "cache-aside" strategy, with
44 * data potentially derived from database rows. Generally speaking, cache data should be treated
45 * as equally up-to-date to data from a replica database, and is thus essentially subject to the
46 * same replication lag.
48 * The primary way to interact with this class is via the getWithSetCallback() method.
50 * Each data center has its own cache cluster, with web servers in a given datacenter
51 * populating and reading from the local datacenter only. The exceptions are methods delete(),
52 * touchCheckKey(), and resetCheckKey(), which also asynchronously broadcast the equivalent
53 * purge to other datacenters.
55 * To learn how this is used and configured at Wikimedia Foundation,
56 * refer to <https://wikitech.wikimedia.org/wiki/Memcached_for_MediaWiki>.
58 * For broader guidance on how to approach caching in MediaWiki at scale,
59 * refer to <https://wikitech.wikimedia.org/wiki/MediaWiki_Engineering/Guides/Backend_performance_practices>.
61 * For your code to "see" new values in a timely manner, you need to follow either the
62 * validation strategy, or the purge strategy.
64 * #### Strategy 1: Validation
66 * The validation strategy refers to the natural avoidance of stale data
67 * by one of the following means:
69 * - A) The cached value is immutable.
71 * If you can obtain all the information needed to uniquely describe the value,
72 * then the value never has to change or be purged. Instead, the key changes,
73 * which naturally creates a miss where you can compute the right value.
74 * For example, a transformation like parsing or transforming some input,
75 * could have a cache key like `example-myparser, option-xyz, v2, hash1234`
76 * which would describe the transformation, the version/parameters, and a hash
77 * of the exact input.
79 * This also naturally avoids oscillation or corruption in the context of multiple
80 * servers and data centers, where your code may not always be running the same version
81 * everywhere at the same time. Newer code would have its own set of cache keys,
82 * ensuring a deterministic outcome.
83 * - B) The value is cached with a low TTL.
85 * If you can tolerate a few seconds or minutes of delay before changes are reflected
86 * in the way your data is used, and if re-computation is quick, you can consider
87 * caching it with a "blind" TTL – using the value's age as your method of validation.
88 * - C) Validity is checked against an external source.
90 * Perhaps you prefer to utilize the old data as fallback or to help compute the new
91 * value, or for other reasons you need to have a stable key across input changes
92 * (e.g. cache by page title instead of revision ID). If you put the variable identifier
93 * (e.g. input hash, or revision ID) in the cache value, and validate this on retrieval
94 * then you don't need purging or expiration.
96 * After calling get() you can validate the ID inside the cached value against what
97 * you know. When needed, recompute the value and call set().
99 * #### Strategy 2: Purge
101 * The purge strategy refers to the approach whereby your application knows that source
102 * data has changed and can react by purging the relevant cache keys.
103 * The simplest purge method is delete().
105 * Note that cache updates and purges are not immediately visible to all application servers in
106 * all data centers. The cache should be treated like a replica database in this regard.
107 * If immediate synchronization is required, then solutions must be sought outside WANCache.
109 * Write operations like delete() and the "set" part of getWithSetCallback(), may return true as
110 * soon as the command has been sent or buffered to an open connection to the cache cluster.
111 * It will be processed and/or broadcasted asynchronously.
113 * @anchor wanobjectcache-deployment
114 * ### Deploying WANObjectCache
116 * There are two supported ways for sysadmins to set up multi-DC cache purging:
118 * - A) Set up mcrouter as the cache backend, with a memcached BagOStuff class for the 'cache'
119 * parameter, and a wildcard routing prefix for the 'broadcastRoutingPrefix' parameter.
120 * Configure mcrouter as follows:
121 * - Define a "<datacenter>" pool of memcached servers for each datacenter.
122 * - Define a "<datacenter>/wan" route to each datacenter, using "AllSyncRoute" for the
123 * routes that go to the local datacenter pool and "AllAsyncRoute" for the routes that
124 * go to remote datacenter pools. The child routes should use "HashRoute|<datacenter>".
125 * This allows for the use of a wildcard route for 'broadcastRoutingPrefix'. See
126 * https://github.com/facebook/mcrouter/wiki/Routing-Prefix and
127 * https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup.
128 * - In order to reroute operations from "down" servers to spare ("gutter") servers, use
129 * "FailoverWithExptimeRoute" (failover_exptime=60) instead of "HashRoute|<datacenter>"
130 * in the "AllSyncRoute"/"AllAsyncRoute" child routes.
131 * The "gutter" pool is a set of memcached servers that only handle failover traffic.
132 * Such servers should be carefully spread over different rows and racks. See
133 * https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles#failoverroute
134 * - B) Set up dynomite as the cache backend, using a memcached BagOStuff class for the 'cache'
135 * parameter. Note that with this setup, all key setting operations will be broadcasted,
136 * rather than just purges. Writes will be eventually consistent via the Dynamo replication
137 * model. See https://github.com/Netflix/dynomite.
139 * Broadcasted operations like delete() and touchCheckKey() are intended to run
140 * immediately in the local datacenter and asynchronously in remote datacenters.
142 * This means that callers in all datacenters may see older values for however many
143 * milliseconds that the purge took to reach that datacenter. As with any cache, this
144 * should not be relied on for cases where reads are used to determine writes to source
145 * (e.g. non-cache) data stores, except when reading immutable data.
147 * Internally, access to a given key actually involves the use of one or more "sister" keys.
148 * A sister key is constructed by prefixing the base key with "WANCache:" (used to distinguish
149 * WANObjectCache formatted keys) and suffixing a colon followed by a single-character sister
150 * key type. The sister key types include the following:
152 * - `v`: used to store "regular" values (metadata-wrapped) and temporary purge "tombstones".
153 * - `t`: used to store "last purge" timestamps for "check" keys.
154 * - `m`: used to store temporary mutex locks to avoid cache stampedes.
155 * - `i`: used to store temporary interim values (metadata-wrapped) for tombstoned keys.
157 * @ingroup Cache
158 * @newable
159 * @since 1.26
161 class WANObjectCache implements
162 ExpirationAwareness,
163 StorageAwareness,
164 IStoreKeyEncoder,
165 LoggerAwareInterface
167 /** @var BagOStuff The local datacenter cache */
168 protected $cache;
169 /** @var MapCacheLRU[] Map of group PHP instance caches */
170 protected $processCaches = [];
171 /** @var LoggerInterface */
172 protected $logger;
173 /** @var StatsFactory */
174 protected $stats;
175 /** @var callable|null Function that takes a WAN cache callback and runs it later */
176 protected $asyncHandler;
179 * Routing prefix for operations that should be broadcasted to all data centers.
181 * If null, the there is only one datacenter or a backend proxy broadcasts everything.
183 * @var string|null
185 protected $broadcastRoute;
186 /** @var bool Whether to use "interim" caching while keys are tombstoned */
187 protected $useInterimHoldOffCaching = true;
188 /** @var float Unix timestamp of the oldest possible valid values */
189 protected $epoch;
190 /** @var string Stable secret used for hashing long strings into key components */
191 protected $secret;
192 /** @var int Scheme to use for key coalescing (Hash Tags or Hash Stops) */
193 protected $coalesceScheme;
195 /** @var array<int,array> List of (key, UNIX timestamp) tuples for get() cache misses */
196 private $missLog;
198 /** @var int Callback stack depth for getWithSetCallback() */
199 private $callbackDepth = 0;
200 /** @var mixed[] Temporary warm-up cache */
201 private $warmupCache = [];
202 /** @var int Key fetched */
203 private $warmupKeyMisses = 0;
205 /** @var float|null */
206 private $wallClockOverride;
208 /** Max expected seconds to pass between delete() and DB commit finishing */
209 private const MAX_COMMIT_DELAY = 3;
210 /** Max expected seconds of combined lag from replication and "view snapshots" */
211 private const MAX_READ_LAG = 7;
212 /** Seconds to tombstone keys on delete() and to treat keys as volatile after purges */
213 public const HOLDOFF_TTL = self::MAX_COMMIT_DELAY + self::MAX_READ_LAG + 1;
215 /** Consider regeneration if the key will expire within this many seconds */
216 private const LOW_TTL = 60;
217 /** Max TTL, in seconds, to store keys when a data source has high replication lag */
218 public const TTL_LAGGED = 30;
220 /** Expected time-till-refresh, in seconds, if the key is accessed once per second */
221 private const HOT_TTR = 900;
222 /** Minimum key age, in seconds, for expected time-till-refresh to be considered */
223 private const AGE_NEW = 60;
225 /** Idiom for getWithSetCallback() meaning "no cache stampede mutex" */
226 private const TSE_NONE = -1;
228 /** Idiom for set()/getWithSetCallback() meaning "no post-expiration persistence" */
229 public const STALE_TTL_NONE = 0;
230 /** Idiom for set()/getWithSetCallback() meaning "no post-expiration grace period" */
231 public const GRACE_TTL_NONE = 0;
232 /** Idiom for delete()/touchCheckKey() meaning "no hold-off period" */
233 public const HOLDOFF_TTL_NONE = 0;
235 /** @var float Idiom for getWithSetCallback() meaning "no minimum required as-of timestamp" */
236 public const MIN_TIMESTAMP_NONE = 0.0;
238 /** Default process cache name and max key count */
239 private const PC_PRIMARY = 'primary:1000';
241 /** Idiom for get()/getMulti() to return extra information by reference */
242 public const PASS_BY_REF = [];
244 /** Use twemproxy-style Hash Tag key scheme (e.g. "{...}") */
245 private const SCHEME_HASH_TAG = 1;
246 /** Use mcrouter-style Hash Stop key scheme (e.g. "...|#|") */
247 private const SCHEME_HASH_STOP = 2;
249 /** Seconds to keep dependency purge keys around */
250 private const CHECK_KEY_TTL = self::TTL_YEAR;
251 /** Seconds to keep interim value keys for tombstoned keys around */
252 private const INTERIM_KEY_TTL = 2;
254 /** Seconds to keep lock keys around */
255 private const LOCK_TTL = 10;
256 /** Seconds to ramp up the chance of regeneration due to expected time-till-refresh */
257 private const RAMPUP_TTL = 30;
259 /** @var float Tiny negative float to use when CTL comes up >= 0 due to clock skew */
260 private const TINY_NEGATIVE = -0.000001;
261 /** @var float Tiny positive float to use when using "minTime" to assert an inequality */
262 private const TINY_POSITIVE = 0.000001;
264 /** Min millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL) */
265 private const RECENT_SET_LOW_MS = 50;
266 /** Max millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL) */
267 private const RECENT_SET_HIGH_MS = 100;
269 /** Consider value generation somewhat high if it takes this many seconds or more */
270 private const GENERATION_HIGH_SEC = 0.2;
272 /** Key to the tombstone entry timestamp */
273 private const PURGE_TIME = 0;
274 /** Key to the tombstone entry hold-off TTL */
275 private const PURGE_HOLDOFF = 1;
277 /** Cache format version number */
278 private const VERSION = 1;
280 /** Version number attribute for a key; keep value for b/c (< 1.36) */
281 public const KEY_VERSION = 'version';
282 /** Generation completion timestamp attribute for a key; keep value for b/c (< 1.36) */
283 public const KEY_AS_OF = 'asOf';
284 /** Logical TTL attribute for a key */
285 public const KEY_TTL = 'ttl';
286 /** Remaining TTL attribute for a key; keep value for b/c (< 1.36) */
287 public const KEY_CUR_TTL = 'curTTL';
288 /** Tomstone timestamp attribute for a key; keep value for b/c (< 1.36) */
289 public const KEY_TOMB_AS_OF = 'tombAsOf';
290 /** Highest "check" key timestamp for a key; keep value for b/c (< 1.36) */
291 public const KEY_CHECK_AS_OF = 'lastCKPurge';
293 /** Value for a key */
294 private const RES_VALUE = 0;
295 /** Version number attribute for a key */
296 private const RES_VERSION = 1;
297 /** Generation completion timestamp attribute for a key */
298 private const RES_AS_OF = 2;
299 /** Logical TTL attribute for a key */
300 private const RES_TTL = 3;
301 /** Tomstone timestamp attribute for a key */
302 private const RES_TOMB_AS_OF = 4;
303 /** Highest "check" key timestamp for a key */
304 private const RES_CHECK_AS_OF = 5;
305 /** Highest "touched" timestamp for a key */
306 private const RES_TOUCH_AS_OF = 6;
307 /** Remaining TTL attribute for a key */
308 private const RES_CUR_TTL = 7;
310 /** Key to WAN cache version number; stored in blobs */
311 private const FLD_FORMAT_VERSION = 0;
312 /** Key to the cached value; stored in blobs */
313 private const FLD_VALUE = 1;
314 /** Key to the original TTL; stored in blobs */
315 private const FLD_TTL = 2;
316 /** Key to the cache timestamp; stored in blobs */
317 private const FLD_TIME = 3;
318 /** Key to the flags bit field (reserved number) */
319 private const /** @noinspection PhpUnusedPrivateFieldInspection */ FLD_FLAGS = 4;
320 /** Key to collection cache version number; stored in blobs */
321 private const FLD_VALUE_VERSION = 5;
322 private const /** @noinspection PhpUnusedPrivateFieldInspection */ FLD_GENERATION_TIME = 6;
324 /** Single character component for value keys */
325 private const TYPE_VALUE = 'v';
326 /** Single character component for timestamp check keys */
327 private const TYPE_TIMESTAMP = 't';
328 /** Single character component for mutex lock keys */
329 private const TYPE_MUTEX = 'm';
330 /** Single character component for interim value keys */
331 private const TYPE_INTERIM = 'i';
333 /** Value prefix of purge values */
334 private const PURGE_VAL_PREFIX = 'PURGED';
337 * @stable to call
338 * @param array $params
339 * - cache : BagOStuff object for a persistent cache
340 * - logger : LoggerInterface object
341 * - stats : StatsFactory object. Since 1.43, constructing a WANObjectCache object
342 * with an IBufferingStatsdDataFactory stats collector will emit a warning.
343 * - asyncHandler : A function that takes a callback and runs it later. If supplied,
344 * whenever a preemptive refresh would be triggered in getWithSetCallback(), the
345 * current cache value is still used instead. However, the async-handler function
346 * receives a WAN cache callback that, when run, will execute the value generation
347 * callback supplied by the getWithSetCallback() caller. The result will be saved
348 * as normal. The handler is expected to call the WAN cache callback at an opportune
349 * time (e.g. HTTP post-send), though generally within a few 100ms. [optional]
350 * - broadcastRoutingPrefix: a routing prefix used to broadcast certain operations to all
351 * datacenters; See also <https://github.com/facebook/mcrouter/wiki/Config-Files>.
352 * This prefix takes the form `/<datacenter>/<name of wan route>/`, where `datacenter`
353 * is usually a wildcard to select all matching routes (e.g. the WAN cluster in all DCs).
354 * See also <https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup>.
355 * This is required when using mcrouter as a multi-region backing store proxy. [optional]
356 * - epoch: lowest UNIX timestamp a value/tombstone must have to be valid. [optional]
357 * - secret: stable secret used for hashing long strings into key components. [optional]
358 * - coalesceScheme: which key scheme to use in order to encourage the backend to place any
359 * "helper" keys for a "value" key within the same cache server. This reduces network
360 * overhead and reduces the chance the single downed cache server causes disruption.
361 * Use "hash_stop" with mcrouter and "hash_tag" with dynomite. [default: "hash_stop"]
363 public function __construct( array $params ) {
364 $this->cache = $params['cache'];
365 $this->broadcastRoute = $params['broadcastRoutingPrefix'] ?? null;
366 $this->epoch = $params['epoch'] ?? 0;
367 $this->secret = $params['secret'] ?? (string)$this->epoch;
368 if ( ( $params['coalesceScheme'] ?? '' ) === 'hash_tag' ) {
369 // https://redis.io/topics/cluster-spec
370 // https://github.com/twitter/twemproxy/blob/v0.4.1/notes/recommendation.md#hash-tags
371 // https://github.com/Netflix/dynomite/blob/v0.7.0/notes/recommendation.md#hash-tags
372 $this->coalesceScheme = self::SCHEME_HASH_TAG;
373 } else {
374 // https://github.com/facebook/mcrouter/wiki/Key-syntax
375 $this->coalesceScheme = self::SCHEME_HASH_STOP;
378 $this->setLogger( $params['logger'] ?? new NullLogger() );
380 if ( isset( $params['stats'] ) && $params['stats'] instanceof IBufferingStatsdDataFactory ) {
381 wfDeprecated(
382 __METHOD__,
383 'Use of StatsdDataFactory is deprecated in 1.43. Use StatsFactory instead.'
385 $params['stats'] = null;
387 $this->stats = $params['stats'] ?? StatsFactory::newNull();
389 $this->asyncHandler = $params['asyncHandler'] ?? null;
390 $this->missLog = array_fill( 0, 10, [ '', 0.0 ] );
394 * @param LoggerInterface $logger
396 public function setLogger( LoggerInterface $logger ) {
397 $this->logger = $logger;
401 * Get an instance that wraps EmptyBagOStuff
403 * @return WANObjectCache
405 public static function newEmpty() {
406 return new static( [ 'cache' => new EmptyBagOStuff() ] );
410 * Fetch the value of a key from cache
412 * If supplied, $curTTL is set to the remaining TTL (current time left):
413 * - a) INF; if $key exists, has no TTL, and is not purged by $checkKeys
414 * - b) float (>=0); if $key exists, has a TTL, and is not purged by $checkKeys
415 * - c) float (<0); if $key is tombstoned, stale, or existing but purged by $checkKeys
416 * - d) null; if $key does not exist and is not tombstoned
418 * If a key is tombstoned, $curTTL will reflect the time since delete().
420 * The timestamp of $key will be checked against the last-purge timestamp
421 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
422 * initialized to the current timestamp. If any of $checkKeys have a timestamp
423 * greater than that of $key, then $curTTL will reflect how long ago $key
424 * became invalid. Callers can use $curTTL to know when the value is stale.
425 * The $checkKeys parameter allow mass key purges by updating a single key:
426 * - a) Each "check" key represents "last purged" of some source data
427 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
428 * - c) When the source data that "check" keys represent changes,
429 * the touchCheckKey() method is called on them
431 * Source data entities might exist in a DB that uses snapshot isolation
432 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
433 * isolation can largely be maintained by doing the following:
434 * - a) Calling delete() on entity change *and* creation, before DB commit
435 * - b) Keeping transaction duration shorter than the delete() hold-off TTL
436 * - c) Disabling interim key caching via useInterimHoldOffCaching() before get() calls
438 * However, pre-snapshot values might still be seen if an update was made
439 * in a remote datacenter but the purge from delete() didn't relay yet.
441 * Consider using getWithSetCallback(), which has cache slam avoidance and key
442 * versioning features, instead of bare get()/set() calls.
444 * Do not use this method on versioned keys accessed via getWithSetCallback().
446 * When using the $info parameter, it should be passed in as WANObjectCache::PASS_BY_REF.
447 * In that case, it becomes a key metadata map. Otherwise, for backwards compatibility,
448 * $info becomes the value generation timestamp (null if the key is nonexistant/tombstoned).
449 * Key metadata map fields include:
450 * - WANObjectCache::KEY_VERSION: value version number; null if key is nonexistant
451 * - WANObjectCache::KEY_AS_OF: value generation timestamp (UNIX); null if key is nonexistant
452 * - WANObjectCache::KEY_TTL: assigned TTL (seconds); null if key is nonexistant/tombstoned
453 * - WANObjectCache::KEY_CUR_TTL: remaining TTL (seconds); null if key is nonexistant
454 * - WANObjectCache::KEY_TOMB_AS_OF: tombstone timestamp (UNIX); null if key is not tombstoned
455 * - WANObjectCache::KEY_CHECK_AS_OF: highest "check" key timestamp (UNIX); null if none
457 * @param string $key Cache key made with makeKey()/makeGlobalKey()
458 * @param float|null &$curTTL Seconds of TTL left [returned]
459 * @param string[] $checkKeys Map of (integer or cache key => "check" key(s));
460 * "check" keys must also be made with makeKey()/makeGlobalKey()
461 * @param array &$info Metadata map [returned]
462 * @return mixed Value of cache key; false on failure
464 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$info = [] ) {
465 // Note that an undeclared variable passed as $info starts as null (not the default).
466 // Also, if no $info parameter is provided, then it doesn't matter how it changes here.
467 $legacyInfo = ( $info !== self::PASS_BY_REF );
469 $now = $this->getCurrentTime();
470 $res = $this->fetchKeys( [ $key ], $checkKeys, $now )[$key];
472 $curTTL = $res[self::RES_CUR_TTL];
473 $info = $legacyInfo
474 ? $res[self::RES_AS_OF]
476 self::KEY_VERSION => $res[self::RES_VERSION],
477 self::KEY_AS_OF => $res[self::RES_AS_OF],
478 self::KEY_TTL => $res[self::RES_TTL],
479 self::KEY_CUR_TTL => $res[self::RES_CUR_TTL],
480 self::KEY_TOMB_AS_OF => $res[self::RES_TOMB_AS_OF],
481 self::KEY_CHECK_AS_OF => $res[self::RES_CHECK_AS_OF]
484 if ( $curTTL === null || $curTTL <= 0 ) {
485 // Log the timestamp in case a corresponding set() call does not provide "walltime"
486 unset( $this->missLog[array_key_first( $this->missLog )] );
487 $this->missLog[] = [ $key, $this->getCurrentTime() ];
490 return $res[self::RES_VALUE];
494 * Fetch the value of several keys from cache
496 * $curTTLs becomes a map of only present/tombstoned $keys to their current time-to-live.
498 * $checkKeys holds the "check" keys used to validate values of applicable keys. The
499 * integer indexes hold "check" keys that apply to all of $keys while the string indexes
500 * hold "check" keys that only apply to the cache key with that name. The logic of "check"
501 * keys otherwise works the same as in WANObjectCache::get().
503 * When using the $info parameter, it should be passed in as WANObjectCache::PASS_BY_REF.
504 * In that case, it becomes a mapping of all the $keys to their metadata maps, each in the
505 * style of WANObjectCache::get(). Otherwise, for backwards compatibility, $info becomes a
506 * map of only present/tombstoned $keys to their value generation timestamps.
508 * @see WANObjectCache::get()
510 * @param string[] $keys List/map with makeKey()/makeGlobalKey() cache keys as values
511 * @param array<string,float> &$curTTLs Map of (key => seconds of TTL left) [returned]
512 * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s));
513 * "check" keys must also be made with makeKey()/makeGlobalKey()
514 * @param array<string,array> &$info Map of (key => metadata map) [returned]
515 * @return array<string,mixed> Map of (key => value) for existing values in order of $keys
517 final public function getMulti(
518 array $keys,
519 &$curTTLs = [],
520 array $checkKeys = [],
521 &$info = []
523 // Note that an undeclared variable passed as $info starts as null (not the default).
524 // Also, if no $info parameter is provided, then it doesn't matter how it changes here.
525 $legacyInfo = ( $info !== self::PASS_BY_REF );
527 $curTTLs = [];
528 $info = [];
529 $valuesByKey = [];
531 $now = $this->getCurrentTime();
532 $resByKey = $this->fetchKeys( $keys, $checkKeys, $now );
533 foreach ( $resByKey as $key => $res ) {
534 if ( $res[self::RES_VALUE] !== false ) {
535 $valuesByKey[$key] = $res[self::RES_VALUE];
538 if ( $res[self::RES_CUR_TTL] !== null ) {
539 $curTTLs[$key] = $res[self::RES_CUR_TTL];
541 $info[$key] = $legacyInfo
542 ? $res[self::RES_AS_OF]
544 self::KEY_VERSION => $res[self::RES_VERSION],
545 self::KEY_AS_OF => $res[self::RES_AS_OF],
546 self::KEY_TTL => $res[self::RES_TTL],
547 self::KEY_CUR_TTL => $res[self::RES_CUR_TTL],
548 self::KEY_TOMB_AS_OF => $res[self::RES_TOMB_AS_OF],
549 self::KEY_CHECK_AS_OF => $res[self::RES_CHECK_AS_OF]
553 return $valuesByKey;
557 * Fetch the value and key metadata of several keys from cache
559 * $checkKeys holds the "check" keys used to validate values of applicable keys.
560 * The integer indexes hold "check" keys that apply to all of $keys while the string
561 * indexes hold "check" keys that only apply to the cache key with that name.
563 * @param string[] $keys List/map with makeKey()/makeGlobalKey() cache keys as values
564 * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s));
565 * "check" keys must also be made with makeKey()/makeGlobalKey()
566 * @param float $now The current UNIX timestamp
567 * @param callable|null $touchedCb Callback yielding a UNIX timestamp from a value, or null
568 * @return array<string,array> Map of (key => WANObjectCache::RESULT_* map) in order of $keys
569 * @note Callable type hints are not used to avoid class-autoloading
571 protected function fetchKeys( array $keys, array $checkKeys, float $now, $touchedCb = null ) {
572 $resByKey = [];
574 // List of all sister keys that need to be fetched from cache
575 $allSisterKeys = [];
576 // Order-corresponding value sister key list for the base key list ($keys)
577 $valueSisterKeys = [];
578 // List of "check" sister keys to compare all value sister keys against
579 $checkSisterKeysForAll = [];
580 // Map of (base key => additional "check" sister key(s) to compare against)
581 $checkSisterKeysByKey = [];
583 foreach ( $keys as $key ) {
584 $sisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE );
585 $allSisterKeys[] = $sisterKey;
586 $valueSisterKeys[] = $sisterKey;
589 foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) {
590 // Note: avoid array_merge() inside loop in case there are many keys
591 if ( is_int( $i ) ) {
592 // Single "check" key that applies to all base keys
593 $sisterKey = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP );
594 $allSisterKeys[] = $sisterKey;
595 $checkSisterKeysForAll[] = $sisterKey;
596 } else {
597 // List of "check" keys that apply to a specific base key
598 foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) {
599 $sisterKey = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP );
600 $allSisterKeys[] = $sisterKey;
601 $checkSisterKeysByKey[$i][] = $sisterKey;
606 if ( $this->warmupCache ) {
607 // Get the wrapped values of the sister keys from the warmup cache
608 $wrappedBySisterKey = $this->warmupCache;
609 $sisterKeysMissing = array_diff( $allSisterKeys, array_keys( $wrappedBySisterKey ) );
610 if ( $sisterKeysMissing ) {
611 $this->warmupKeyMisses += count( $sisterKeysMissing );
612 $wrappedBySisterKey += $this->cache->getMulti( $sisterKeysMissing );
614 } else {
615 // Fetch the wrapped values of the sister keys from the backend
616 $wrappedBySisterKey = $this->cache->getMulti( $allSisterKeys );
619 // List of "check" sister key purge timestamps to compare all value sister keys against
620 $ckPurgesForAll = $this->processCheckKeys(
621 $checkSisterKeysForAll,
622 $wrappedBySisterKey,
623 $now
625 // Map of (base key => extra "check" sister key purge timestamp(s) to compare against)
626 $ckPurgesByKey = [];
627 foreach ( $checkSisterKeysByKey as $keyWithCheckKeys => $checkKeysForKey ) {
628 $ckPurgesByKey[$keyWithCheckKeys] = $this->processCheckKeys(
629 $checkKeysForKey,
630 $wrappedBySisterKey,
631 $now
635 // Unwrap and validate any value found for each base key (under the value sister key)
636 foreach (
637 array_map( null, $valueSisterKeys, $keys )
638 as [ $valueSisterKey, $key ]
640 if ( array_key_exists( $valueSisterKey, $wrappedBySisterKey ) ) {
641 // Key exists as either a live value or tombstone value
642 $wrapped = $wrappedBySisterKey[$valueSisterKey];
643 } else {
644 // Key does not exist
645 $wrapped = false;
648 $res = $this->unwrap( $wrapped, $now );
649 $value = $res[self::RES_VALUE];
651 foreach ( array_merge( $ckPurgesForAll, $ckPurgesByKey[$key] ?? [] ) as $ckPurge ) {
652 $res[self::RES_CHECK_AS_OF] = max(
653 $ckPurge[self::PURGE_TIME],
654 $res[self::RES_CHECK_AS_OF]
656 // Timestamp marking the end of the hold-off period for this purge
657 $holdoffDeadline = $ckPurge[self::PURGE_TIME] + $ckPurge[self::PURGE_HOLDOFF];
658 // Check if the value was generated during the hold-off period
659 if ( $value !== false && $holdoffDeadline >= $res[self::RES_AS_OF] ) {
660 // How long ago this value was purged by *this* "check" key
661 $ago = min( $ckPurge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
662 // How long ago this value was purged by *any* known "check" key
663 $res[self::RES_CUR_TTL] = min( $res[self::RES_CUR_TTL], $ago );
667 if ( $touchedCb !== null && $value !== false ) {
668 $touched = $touchedCb( $value );
669 if ( $touched !== null && $touched >= $res[self::RES_AS_OF] ) {
670 $res[self::RES_CUR_TTL] = min(
671 $res[self::RES_CUR_TTL],
672 $res[self::RES_AS_OF] - $touched,
673 self::TINY_NEGATIVE
676 } else {
677 $touched = null;
680 $res[self::RES_TOUCH_AS_OF] = max( $res[self::RES_TOUCH_AS_OF], $touched );
682 $resByKey[$key] = $res;
685 return $resByKey;
689 * @param string[] $checkSisterKeys List of "check" sister keys
690 * @param mixed[] $wrappedBySisterKey Preloaded map of (sister key => wrapped value)
691 * @param float $now UNIX timestamp
692 * @return array[] List of purge value arrays
694 private function processCheckKeys(
695 array $checkSisterKeys,
696 array $wrappedBySisterKey,
697 float $now
699 $purges = [];
701 foreach ( $checkSisterKeys as $timeKey ) {
702 $purge = isset( $wrappedBySisterKey[$timeKey] )
703 ? $this->parsePurgeValue( $wrappedBySisterKey[$timeKey] )
704 : null;
706 if ( $purge === null ) {
707 // No holdoff when lazy creating a check key, use cache right away (T344191)
708 $wrapped = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL_NONE, $purge );
709 $this->cache->add(
710 $timeKey,
711 $wrapped,
712 self::CHECK_KEY_TTL,
713 $this->cache::WRITE_BACKGROUND
717 $purges[] = $purge;
720 return $purges;
724 * Set the value of a key in cache
726 * Simply calling this method when source data changes is not valid because
727 * the changes do not replicate to the other WAN sites. In that case, delete()
728 * should be used instead. This method is intended for use on cache misses.
730 * If data was read using "view snapshots" (e.g. innodb REPEATABLE-READ),
731 * use 'since' to avoid the following race condition:
732 * - a) T1 starts
733 * - b) T2 updates a row, calls delete(), and commits
734 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
735 * - d) T1 reads the row and calls set() due to a cache miss
736 * - e) Stale value is stuck in cache
738 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
740 * Be aware that this does not update the process cache for getWithSetCallback()
741 * callers. Keys accessed via that method are not generally meant to also be set
742 * using this primitive method.
744 * Consider using getWithSetCallback(), which has cache slam avoidance and key
745 * versioning features, instead of bare get()/set() calls.
747 * Do not use this method on versioned keys accessed via getWithSetCallback().
749 * Example usage:
750 * @code
751 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
752 * $setOpts = Database::getCacheSetOptions( $dbr );
753 * // Fetch the row from the DB
754 * $row = $dbr->selectRow( ... );
755 * $key = $cache->makeKey( 'building', $buildingId );
756 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
757 * @endcode
759 * @param string $key Cache key made with makeKey()/makeGlobalKey()
760 * @param mixed $value Value to set for the cache key
761 * @param int $ttl Seconds to live. Special values are:
762 * - WANObjectCache::TTL_INDEFINITE: Cache forever (default)
763 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
764 * @param array $opts Options map:
765 * - lag: Highest seconds of replication lag potentially affecting reads used to generate
766 * the value. This should not be affected by the duration of transaction "view snapshots"
767 * (e.g. innodb REPEATABLE-READ) nor the time elapsed since the first read (though both
768 * increase staleness). For reads using view snapshots, only the replication lag during
769 * snapshot initialization matters. Use false if replication is stopped/broken on a
770 * replica server involved in the reads.
771 * Default: 0 seconds
772 * - since: UNIX timestamp indicative of the highest possible staleness caused by the
773 * duration of transaction "view snapshots" (e.g. innodb REPEATABLE-READ) and the time
774 * elapsed since the first read. This should not be affected by replication lag.
775 * Default: 0 seconds
776 * - pending: Whether this data is possibly from an uncommitted write transaction.
777 * Generally, other threads should not see values from the future and
778 * they certainly should not see ones that ended up getting rolled back.
779 * Default: false
780 * - lockTSE: If excessive replication/snapshot lag is detected, then store the value
781 * with this TTL and flag it as stale. This is only useful if the reads for this key
782 * use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set
783 * then it will still add on to this TTL in the excessive lag scenario.
784 * Default: WANObjectCache::TSE_NONE
785 * - staleTTL: Seconds to keep the key around if it is stale. The get()/getMulti()
786 * methods return such stale values with a $curTTL of 0, and getWithSetCallback()
787 * will call the generation callback in such cases, passing in the old value
788 * and its as-of time to the callback. This is useful if adaptiveTTL() is used
789 * on the old value's as-of time when it is verified as still being correct.
790 * Default: WANObjectCache::STALE_TTL_NONE
791 * - segmentable: Allow partitioning of the value if it is a large string.
792 * Default: false.
793 * - creating: Optimize for the case where the key does not already exist.
794 * Default: false
795 * - version: Integer version number signifying the format of the value.
796 * Default: null
797 * - walltime: How long the value took to generate in seconds. Default: null
798 * @phpcs:ignore Generic.Files.LineLength
799 * @phan-param array{lag?:float|int,since?:float|int,pending?:bool,lockTSE?:int,staleTTL?:int,creating?:bool,version?:int,walltime?:int|float,segmentable?:bool} $opts
800 * @note Options added in 1.28: staleTTL
801 * @note Options added in 1.33: creating
802 * @note Options added in 1.34: version, walltime
803 * @note Options added in 1.40: segmentable
804 * @return bool Success
806 final public function set( $key, $value, $ttl = self::TTL_INDEFINITE, array $opts = [] ) {
807 $keygroup = $this->determineKeyGroupForStats( $key );
809 $ok = $this->setMainValue(
810 $key,
811 $value,
812 $ttl,
813 $opts['version'] ?? null,
814 $opts['walltime'] ?? null,
815 $opts['lag'] ?? 0,
816 $opts['since'] ?? null,
817 $opts['pending'] ?? false,
818 $opts['lockTSE'] ?? self::TSE_NONE,
819 $opts['staleTTL'] ?? self::STALE_TTL_NONE,
820 $opts['segmentable'] ?? false,
821 $opts['creating'] ?? false
824 $this->stats->getCounter( 'wanobjectcache_set_total' )
825 ->setLabel( 'keygroup', $keygroup )
826 ->setLabel( 'result', ( $ok ? 'ok' : 'error' ) )
827 ->copyToStatsdAt( "wanobjectcache.$keygroup.set." . ( $ok ? 'ok' : 'error' ) )
828 ->increment();
830 return $ok;
834 * @param string $key Cache key made with makeKey()/makeGlobalKey()
835 * @param mixed $value
836 * @param int|float $ttl
837 * @param int|null $version
838 * @param float|null $walltime
839 * @param float|int|bool $dataReplicaLag
840 * @param float|int|null $dataReadSince
841 * @param bool $dataPendingCommit
842 * @param int $lockTSE
843 * @param int $staleTTL
844 * @param bool $segmentable
845 * @param bool $creating
846 * @return bool Success
848 private function setMainValue(
849 $key,
850 $value,
851 $ttl,
852 ?int $version,
853 ?float $walltime,
854 $dataReplicaLag,
855 $dataReadSince,
856 bool $dataPendingCommit,
857 int $lockTSE,
858 int $staleTTL,
859 bool $segmentable,
860 bool $creating
862 if ( $ttl < 0 ) {
863 // not cacheable
864 return true;
867 $now = $this->getCurrentTime();
868 $ttl = (int)$ttl;
869 $walltime ??= $this->timeSinceLoggedMiss( $key, $now );
870 $dataSnapshotLag = ( $dataReadSince !== null ) ? max( 0, $now - $dataReadSince ) : 0;
871 $dataCombinedLag = $dataReplicaLag + $dataSnapshotLag;
873 // Forbid caching data that only exists within an uncommitted transaction. Also, lower
874 // the TTL when the data has a "since" time so far in the past that a delete() tombstone,
875 // made after that time, could have already expired (the key is no longer write-holed).
876 // The mitigation TTL depends on whether this data lag is assumed to systemically effect
877 // regeneration attempts in the near future. The TTL also reflects regeneration wall time.
878 if ( $dataPendingCommit ) {
879 // Case A: data comes from an uncommitted write transaction
880 $mitigated = 'pending writes';
881 // Data might never be committed; rely on a less problematic regeneration attempt
882 $mitigationTTL = self::TTL_UNCACHEABLE;
883 } elseif ( $dataSnapshotLag > self::MAX_READ_LAG ) {
884 // Case B: high snapshot lag
885 $pregenSnapshotLag = ( $walltime !== null ) ? ( $dataSnapshotLag - $walltime ) : 0;
886 if ( ( $pregenSnapshotLag + self::GENERATION_HIGH_SEC ) > self::MAX_READ_LAG ) {
887 // Case B1: generation started when transaction duration was already long
888 $mitigated = 'snapshot lag (late generation)';
889 // Probably non-systemic; rely on a less problematic regeneration attempt
890 $mitigationTTL = self::TTL_UNCACHEABLE;
891 } else {
892 // Case B2: slow generation made transaction duration long
893 $mitigated = 'snapshot lag (high generation time)';
894 // Probably systemic; use a low TTL to avoid stampedes/uncacheability
895 $mitigationTTL = self::TTL_LAGGED;
897 } elseif ( $dataReplicaLag === false || $dataReplicaLag > self::MAX_READ_LAG ) {
898 // Case C: low/medium snapshot lag with high replication lag
899 $mitigated = 'replication lag';
900 // Probably systemic; use a low TTL to avoid stampedes/uncacheability
901 $mitigationTTL = self::TTL_LAGGED;
902 } elseif ( $dataCombinedLag > self::MAX_READ_LAG ) {
903 $pregenCombinedLag = ( $walltime !== null ) ? ( $dataCombinedLag - $walltime ) : 0;
904 // Case D: medium snapshot lag with medium replication lag
905 if ( ( $pregenCombinedLag + self::GENERATION_HIGH_SEC ) > self::MAX_READ_LAG ) {
906 // Case D1: generation started when read lag was too high
907 $mitigated = 'read lag (late generation)';
908 // Probably non-systemic; rely on a less problematic regeneration attempt
909 $mitigationTTL = self::TTL_UNCACHEABLE;
910 } else {
911 // Case D2: slow generation made read lag too high
912 $mitigated = 'read lag (high generation time)';
913 // Probably systemic; use a low TTL to avoid stampedes/uncacheability
914 $mitigationTTL = self::TTL_LAGGED;
916 } else {
917 // Case E: new value generated with recent data
918 $mitigated = null;
919 // Nothing to mitigate
920 $mitigationTTL = null;
923 if ( $mitigationTTL === self::TTL_UNCACHEABLE ) {
924 $this->logger->warning(
925 "Rejected set() for {cachekey} due to $mitigated.",
927 'cachekey' => $key,
928 'lag' => $dataReplicaLag,
929 'age' => $dataSnapshotLag,
930 'walltime' => $walltime
934 // no-op the write for being unsafe
935 return true;
938 // TTL to use in staleness checks (does not effect persistence layer TTL)
939 $logicalTTL = null;
941 if ( $mitigationTTL !== null ) {
942 // New value was generated from data that is old enough to be risky
943 if ( $lockTSE >= 0 ) {
944 // Persist the value as long as normal, but make it count as stale sooner
945 $logicalTTL = min( $ttl ?: INF, $mitigationTTL );
946 } else {
947 // Persist the value for a shorter duration
948 $ttl = min( $ttl ?: INF, $mitigationTTL );
951 $this->logger->warning(
952 "Lowered set() TTL for {cachekey} due to $mitigated.",
954 'cachekey' => $key,
955 'lag' => $dataReplicaLag,
956 'age' => $dataSnapshotLag,
957 'walltime' => $walltime
962 // Wrap that value with time/TTL/version metadata
963 $wrapped = $this->wrap( $value, $logicalTTL ?: $ttl, $version, $now );
964 $storeTTL = $ttl + $staleTTL;
966 $flags = $this->cache::WRITE_BACKGROUND;
967 if ( $segmentable ) {
968 $flags |= $this->cache::WRITE_ALLOW_SEGMENTS;
971 if ( $creating ) {
972 $ok = $this->cache->add(
973 $this->makeSisterKey( $key, self::TYPE_VALUE ),
974 $wrapped,
975 $storeTTL,
976 $flags
978 } else {
979 $ok = $this->cache->merge(
980 $this->makeSisterKey( $key, self::TYPE_VALUE ),
981 static function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
982 // A string value means that it is a tombstone; do nothing in that case
983 return ( is_string( $cWrapped ) ) ? false : $wrapped;
985 $storeTTL,
986 $this->cache::MAX_CONFLICTS_ONE,
987 $flags
991 return $ok;
995 * Purge a key from all datacenters
997 * This should only be called when the underlying data (being cached)
998 * changes in a significant way. This deletes the key and starts a hold-off
999 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
1000 * This is done to avoid the following race condition:
1001 * - a) Some DB data changes and delete() is called on a corresponding key
1002 * - b) A request refills the key with a stale value from a lagged DB
1003 * - c) The stale value is stuck there until the key is expired/evicted
1005 * This is implemented by storing a special "tombstone" value at the cache
1006 * key that this class recognizes; get() calls will return false for the key
1007 * and any set() calls will refuse to replace tombstone values at the key.
1008 * For this to always avoid stale value writes, the following must hold:
1009 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
1010 * - b) If lag is higher, the DB will have gone into read-only mode already
1012 * Note that set() can also be lag-aware and lower the TTL if it's high.
1014 * Be aware that this does not clear the process cache. Even if it did, callbacks
1015 * used by getWithSetCallback() might still return stale data in the case of either
1016 * uncommitted or not-yet-replicated changes (callback generally use replica DBs).
1018 * When using potentially long-running ACID transactions, a good pattern is
1019 * to use a pre-commit hook to issue the delete(). This means that immediately
1020 * after commit, callers will see the tombstone in cache upon purge relay.
1021 * It also avoids the following race condition:
1022 * - a) T1 begins, changes a row, and calls delete()
1023 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
1024 * - c) T2 starts, reads the row and calls set() due to a cache miss
1025 * - d) T1 finally commits
1026 * - e) Stale value is stuck in cache
1028 * Example usage:
1029 * @code
1030 * $dbw->startAtomic( __METHOD__ ); // start of request
1031 * ... <execute some stuff> ...
1032 * // Update the row in the DB
1033 * $dbw->update( ... );
1034 * $key = $cache->makeKey( 'homes', $homeId );
1035 * // Purge the corresponding cache entry just before committing
1036 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
1037 * $cache->delete( $key );
1038 * } );
1039 * ... <execute some stuff> ...
1040 * $dbw->endAtomic( __METHOD__ ); // end of request
1041 * @endcode
1043 * The $ttl parameter can be used when purging values that have not actually changed
1044 * recently. For example, user-requested purges or cache cleanup scripts might not need
1045 * to invoke a hold-off period on cache backfills, so they can use HOLDOFF_TTL_NONE.
1047 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
1049 * If called twice on the same key, then the last hold-off TTL takes precedence. For
1050 * idempotence, the $ttl should not vary for different delete() calls on the same key.
1052 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1053 * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
1054 * @return bool True if the item was purged or not found, false on failure
1056 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
1057 // Purge values must be stored under the value key so that WANObjectCache::set()
1058 // can atomically merge values without accidentally undoing a recent purge and thus
1059 // violating the holdoff TTL restriction.
1060 $valueSisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE );
1062 if ( $ttl <= 0 ) {
1063 // A client or cache cleanup script is requesting a cache purge, so there is no
1064 // volatility period due to replica DB lag. Any recent change to an entity cached
1065 // in this key should have triggered an appropriate purge event.
1066 $ok = $this->relayNonVolatilePurge( $valueSisterKey );
1067 } else {
1068 // A cacheable entity recently changed, so there might be a volatility period due
1069 // to replica DB lag. Clients usually expect their actions to be reflected in any
1070 // of their subsequent web request. This is attainable if (a) purge relay lag is
1071 // lower than the time it takes for subsequent request by the client to arrive,
1072 // and, (b) DB replica queries have "read-your-writes" consistency due to DB lag
1073 // mitigation systems.
1074 $now = $this->getCurrentTime();
1075 // Set the key to the purge value in all datacenters
1076 $purge = $this->makeTombstonePurgeValue( $now );
1077 $ok = $this->relayVolatilePurge( $valueSisterKey, $purge, $ttl );
1080 $keygroup = $this->determineKeyGroupForStats( $key );
1082 $this->stats->getCounter( 'wanobjectcache_delete_total' )
1083 ->setLabel( 'keygroup', $keygroup )
1084 ->setLabel( 'result', ( $ok ? 'ok' : 'error' ) )
1085 ->copyToStatsdAt( "wanobjectcache.$keygroup.delete." . ( $ok ? 'ok' : 'error' ) )
1086 ->increment();
1088 return $ok;
1092 * Fetch the value of a timestamp "check" key
1094 * The key will be *initialized* to the current time if not set,
1095 * so only call this method if this behavior is actually desired
1097 * The timestamp can be used to check whether a cached value is valid.
1098 * Callers should not assume that this returns the same timestamp in
1099 * all datacenters due to relay delays.
1101 * The level of staleness can roughly be estimated from this key, but
1102 * if the key was evicted from cache, such calculations may show the
1103 * time since expiry as ~0 seconds.
1105 * Note that "check" keys won't collide with other regular keys.
1107 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1108 * @return float UNIX timestamp
1110 final public function getCheckKeyTime( $key ) {
1111 return $this->getMultiCheckKeyTime( [ $key ] )[$key];
1115 * Fetch the values of each timestamp "check" key
1117 * This works like getCheckKeyTime() except it takes a list of keys
1118 * and returns a map of timestamps instead of just that of one key
1120 * This might be useful if both:
1121 * - a) a class of entities each depend on hundreds of other entities
1122 * - b) these other entities are depended upon by millions of entities
1124 * The later entities can each use a "check" key to purge their dependee entities.
1125 * However, it is expensive for the former entities to verify against all of the relevant
1126 * "check" keys during each getWithSetCallback() call. A less expensive approach is to do
1127 * these verifications only after a "time-till-verify" (TTV) has passed. This is a middle
1128 * ground between using blind TTLs and using constant verification. The adaptiveTTL() method
1129 * can be used to dynamically adjust the TTV. Also, the initial TTV can make use of the
1130 * last-modified times of the dependent entities (either from the DB or the "check" keys).
1132 * Example usage:
1133 * @code
1134 * $value = $cache->getWithSetCallback(
1135 * $cache->makeGlobalKey( 'wikibase-item', $id ),
1136 * self::INITIAL_TTV, // initial time-till-verify
1137 * function ( $oldValue, &$ttv, &$setOpts, $oldAsOf ) use ( $checkKeys, $cache ) {
1138 * $now = microtime( true );
1139 * // Use $oldValue if it passes max ultimate age and "check" key comparisons
1140 * if ( $oldValue &&
1141 * $oldAsOf > max( $cache->getMultiCheckKeyTime( $checkKeys ) ) &&
1142 * ( $now - $oldValue['ctime'] ) <= self::MAX_CACHE_AGE
1143 * ) {
1144 * // Increase time-till-verify by 50% of last time to reduce overhead
1145 * $ttv = $cache->adaptiveTTL( $oldAsOf, self::MAX_TTV, self::MIN_TTV, 1.5 );
1146 * // Unlike $oldAsOf, "ctime" is the ultimate age of the cached data
1147 * return $oldValue;
1150 * $mtimes = []; // dependency last-modified times; passed by reference
1151 * $value = [ 'data' => $this->fetchEntityData( $mtimes ), 'ctime' => $now ];
1152 * // Guess time-till-change among the dependencies, e.g. 1/(total change rate)
1153 * $ttc = 1 / array_sum( array_map(
1154 * function ( $mtime ) use ( $now ) {
1155 * return 1 / ( $mtime ? ( $now - $mtime ) : 900 );
1156 * },
1157 * $mtimes
1158 * ) );
1159 * // The time-to-verify should not be overly pessimistic nor optimistic
1160 * $ttv = min( max( $ttc, self::MIN_TTV ), self::MAX_TTV );
1162 * return $value;
1163 * },
1164 * [ 'staleTTL' => $cache::TTL_DAY ] // keep around to verify and re-save
1165 * );
1166 * @endcode
1168 * @see WANObjectCache::getCheckKeyTime()
1169 * @see WANObjectCache::getWithSetCallback()
1171 * @param string[] $keys Cache keys made with makeKey()/makeGlobalKey()
1172 * @return float[] Map of (key => UNIX timestamp)
1173 * @since 1.31
1175 final public function getMultiCheckKeyTime( array $keys ) {
1176 $checkSisterKeysByKey = [];
1177 foreach ( $keys as $key ) {
1178 $checkSisterKeysByKey[$key] = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1181 $wrappedBySisterKey = $this->cache->getMulti( $checkSisterKeysByKey );
1182 $wrappedBySisterKey += array_fill_keys( $checkSisterKeysByKey, false );
1184 $now = $this->getCurrentTime();
1185 $times = [];
1186 foreach ( $checkSisterKeysByKey as $key => $checkSisterKey ) {
1187 $purge = $this->parsePurgeValue( $wrappedBySisterKey[$checkSisterKey] );
1188 if ( $purge === null ) {
1189 $wrapped = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL_NONE, $purge );
1190 $this->cache->add(
1191 $checkSisterKey,
1192 $wrapped,
1193 self::CHECK_KEY_TTL,
1194 $this->cache::WRITE_BACKGROUND
1198 $times[$key] = $purge[self::PURGE_TIME];
1201 return $times;
1205 * Increase the last-purge timestamp of a "check" key in all datacenters
1207 * This method should only be called when some heavily referenced data changes in
1208 * a significant way, such that it is impractical to call delete() on all the cache
1209 * keys that should be purged. The get*() method calls used to fetch these keys must
1210 * include the given "check" key in the relevant "check" keys argument/option.
1212 * A "check" key essentially represents a last-modified time of an entity. When the
1213 * key is touched, the timestamp will be updated to the current time. Keys fetched
1214 * using get*() calls, that include the "check" key, will be seen as purged.
1216 * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the
1217 * future by get*() methods in order to avoid race conditions where keys are updated
1218 * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check"
1219 * key, making it possible to know the timestamp of the last change to the corresponding
1220 * entities in most cases. This might use more cache space than resetCheckKey().
1222 * When a few important keys get a large number of hits, a high cache time is usually
1223 * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate
1224 * in such cases since the "time since expiry" cannot be inferred, causing any get()
1225 * after the reset to treat the key as being "hot", resulting in more stale value usage.
1227 * Note that "check" keys won't collide with other regular keys.
1229 * @see WANObjectCache::get()
1230 * @see WANObjectCache::getWithSetCallback()
1231 * @see WANObjectCache::resetCheckKey()
1233 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1234 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_TTL_NONE constant
1235 * @return bool True if the item was purged or not found, false on failure
1237 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
1238 $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1240 $now = $this->getCurrentTime();
1241 $purge = $this->makeCheckPurgeValue( $now, $holdoff );
1242 $ok = $this->relayVolatilePurge( $checkSisterKey, $purge, self::CHECK_KEY_TTL );
1244 $keygroup = $this->determineKeyGroupForStats( $key );
1246 $this->stats->getCounter( 'wanobjectcache_check_total' )
1247 ->setLabel( 'keygroup', $keygroup )
1248 ->setLabel( 'result', ( $ok ? 'ok' : 'error' ) )
1249 ->copyToStatsdAt( "wanobjectcache.$keygroup.ck_touch." . ( $ok ? 'ok' : 'error' ) )
1250 ->increment();
1252 return $ok;
1256 * Clear the last-purge timestamp of a "check" key in all datacenters
1258 * Similar to touchCheckKey(), in that keys fetched using get*() calls, that include
1259 * the given "check" key, will be seen as purged. However, there are some differences:
1260 * - a) The "check" key will be deleted from all caches and lazily
1261 * re-initialized when accessed (rather than set everywhere)
1262 * - b) Thus, dependent keys will be known to be stale, but not
1263 * for how long (they are treated as "just" purged), which
1264 * effects any lockTSE logic in getWithSetCallback()
1265 * - c) Since "check" keys are initialized only on the server the key hashes
1266 * to, any temporary ejection of that server will cause the value to be
1267 * seen as purged as a new server will initialize the "check" key.
1269 * The advantage over touchCheckKey() is that the "check" keys, which have high TTLs,
1270 * will only be created when a get*() method actually uses those keys. This is better
1271 * when a large number of "check" keys must be changed in a short period of time.
1273 * Note that "check" keys won't collide with other regular keys.
1275 * @see WANObjectCache::get()
1276 * @see WANObjectCache::getWithSetCallback()
1277 * @see WANObjectCache::touchCheckKey()
1279 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1280 * @return bool True if the item was purged or not found, false on failure
1282 final public function resetCheckKey( $key ) {
1283 $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1284 $ok = $this->relayNonVolatilePurge( $checkSisterKey );
1286 $keygroup = $this->determineKeyGroupForStats( $key );
1288 $this->stats->getCounter( 'wanobjectcache_reset_total' )
1289 ->setLabel( 'keygroup', $keygroup )
1290 ->setLabel( 'result', ( $ok ? 'ok' : 'error' ) )
1291 ->copyToStatsdAt( "wanobjectcache.$keygroup.ck_reset." . ( $ok ? 'ok' : 'error' ) )
1292 ->increment();
1294 return $ok;
1298 * Method to fetch/regenerate a cache key
1300 * On cache miss, the key will be set to the callback result via set()
1301 * (unless the callback returns false) and that result will be returned.
1302 * The arguments supplied to the callback are:
1303 * - $oldValue: prior cache value or false if none was present
1304 * - &$ttl: alterable reference to the TTL to be assigned to the new value
1305 * - &$setOpts: alterable reference to the set() options to be used with the new value
1306 * - $oldAsOf: generation UNIX timestamp of $oldValue or null if not present (since 1.28)
1307 * - $params: custom field/value map as defined by $cbParams (since 1.35)
1309 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
1310 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
1311 * value, but it can be used to maintain "most recent X" values that come from time or
1312 * sequence based source data, provided that the "as of" id/time is tracked. Note that
1313 * preemptive regeneration and $checkKeys can result in a non-false current value.
1315 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
1316 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
1317 * regeneration will automatically be triggered using the callback.
1319 * The $ttl argument and "hotTTR" option (in $opts) use time-dependent randomization
1320 * to avoid stampedes. Keys that are slow to regenerate and either heavily used
1321 * or subject to explicit (unpredictable) purges, may need additional mechanisms.
1322 * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts).
1323 * If explicit purges are needed, also:
1324 * - a) Pass $key into $checkKeys
1325 * - b) Use touchCheckKey( $key ) instead of delete( $key )
1327 * This applies cache server I/O stampede protection against duplicate cache sets.
1328 * This is important when the callback is slow and/or yields large values for a key.
1330 * Example usage (typical key):
1331 * @code
1332 * $catInfo = $cache->getWithSetCallback(
1333 * // Key to store the cached value under
1334 * $cache->makeKey( 'cat-attributes', $catId ),
1335 * // Time-to-live (in seconds)
1336 * $cache::TTL_MINUTE,
1337 * // Function that derives the new key value
1338 * function ( $oldValue, &$ttl, array &$setOpts ) {
1339 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1340 * // Account for any snapshot/replica DB lag
1341 * $setOpts += Database::getCacheSetOptions( $dbr );
1343 * return $dbr->selectRow( ... );
1345 * );
1346 * @endcode
1348 * Example usage (key that is expensive and hot):
1349 * @code
1350 * $catConfig = $cache->getWithSetCallback(
1351 * // Key to store the cached value under
1352 * $cache->makeKey( 'site-cat-config' ),
1353 * // Time-to-live (in seconds)
1354 * $cache::TTL_DAY,
1355 * // Function that derives the new key value
1356 * function ( $oldValue, &$ttl, array &$setOpts ) {
1357 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1358 * // Account for any snapshot/replica DB lag
1359 * $setOpts += Database::getCacheSetOptions( $dbr );
1361 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
1362 * },
1364 * // Calling touchCheckKey() on this key purges the cache
1365 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
1366 * // Try to only let one datacenter thread manage cache updates at a time
1367 * 'lockTSE' => 30,
1368 * // Avoid querying cache servers multiple times in a web request
1369 * 'pcTTL' => $cache::TTL_PROC_LONG
1371 * );
1372 * @endcode
1374 * Example usage (key with dynamic dependencies):
1375 * @code
1376 * $catState = $cache->getWithSetCallback(
1377 * // Key to store the cached value under
1378 * $cache->makeKey( 'cat-state', $cat->getId() ),
1379 * // Time-to-live (seconds)
1380 * $cache::TTL_HOUR,
1381 * // Function that derives the new key value
1382 * function ( $oldValue, &$ttl, array &$setOpts ) {
1383 * // Determine new value from the DB
1384 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1385 * // Account for any snapshot/replica DB lag
1386 * $setOpts += Database::getCacheSetOptions( $dbr );
1388 * return CatState::newFromResults( $dbr->select( ... ) );
1389 * },
1391 * // The "check" keys that represent things the value depends on;
1392 * // Calling touchCheckKey() on any of them purges the cache
1393 * 'checkKeys' => [
1394 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
1395 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
1396 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
1399 * );
1400 * @endcode
1402 * Example usage (key that is expensive with too many DB dependencies for "check" keys):
1403 * @code
1404 * $catToys = $cache->getWithSetCallback(
1405 * // Key to store the cached value under
1406 * $cache->makeKey( 'cat-toys', $catId ),
1407 * // Time-to-live (seconds)
1408 * $cache::TTL_HOUR,
1409 * // Function that derives the new key value
1410 * function ( $oldValue, &$ttl, array &$setOpts ) {
1411 * // Determine new value from the DB
1412 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1413 * // Account for any snapshot/replica DB lag
1414 * $setOpts += Database::getCacheSetOptions( $dbr );
1416 * return CatToys::newFromResults( $dbr->select( ... ) );
1417 * },
1419 * // Get the highest timestamp of any of the cat's toys
1420 * 'touchedCallback' => function ( $value ) use ( $catId ) {
1421 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1422 * $ts = $dbr->selectField( 'cat_toys', 'MAX(ct_touched)', ... );
1424 * return wfTimestampOrNull( TS_UNIX, $ts );
1425 * },
1426 * // Avoid DB queries for repeated access
1427 * 'pcTTL' => $cache::TTL_PROC_SHORT
1429 * );
1430 * @endcode
1432 * Example usage (hot key holding most recent 100 events):
1433 * @code
1434 * $lastCatActions = $cache->getWithSetCallback(
1435 * // Key to store the cached value under
1436 * $cache->makeKey( 'cat-last-actions', 100 ),
1437 * // Time-to-live (in seconds)
1438 * 10,
1439 * // Function that derives the new key value
1440 * function ( $oldValue, &$ttl, array &$setOpts ) {
1441 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
1442 * // Account for any snapshot/replica DB lag
1443 * $setOpts += Database::getCacheSetOptions( $dbr );
1445 * // Start off with the last cached list
1446 * $list = $oldValue ?: [];
1447 * // Fetch the last 100 relevant rows in descending order;
1448 * // only fetch rows newer than $list[0] to reduce scanning
1449 * $rows = iterator_to_array( $dbr->select( ... ) );
1450 * // Merge them and get the new "last 100" rows
1451 * return array_slice( array_merge( $new, $list ), 0, 100 );
1452 * },
1454 * // Try to only let one datacenter thread manage cache updates at a time
1455 * 'lockTSE' => 30,
1456 * // Use a magic value when no cache value is ready rather than stampeding
1457 * 'busyValue' => 'computing'
1459 * );
1460 * @endcode
1462 * Example usage (key holding an LRU subkey:value map; this can avoid flooding cache with
1463 * keys for an unlimited set of (constraint,situation) pairs, thereby avoiding elevated
1464 * cache evictions and wasted memory):
1465 * @code
1466 * $catSituationTolerabilityCache = $this->cache->getWithSetCallback(
1467 * // Group by constraint ID/hash, cat family ID/hash, or something else useful
1468 * $this->cache->makeKey( 'cat-situation-tolerability-checks', $groupKey ),
1469 * WANObjectCache::TTL_DAY, // rarely used groups should fade away
1470 * // The $scenarioKey format is $constraintId:<ID/hash of $situation>
1471 * function ( $cacheMap ) use ( $scenarioKey, $constraintId, $situation ) {
1472 * $lruCache = MapCacheLRU::newFromArray( $cacheMap ?: [], self::CACHE_SIZE );
1473 * $result = $lruCache->get( $scenarioKey ); // triggers LRU bump if present
1474 * if ( $result === null || $this->isScenarioResultExpired( $result ) ) {
1475 * $result = $this->checkScenarioTolerability( $constraintId, $situation );
1476 * $lruCache->set( $scenarioKey, $result, 3 / 8 );
1478 * // Save the new LRU cache map and reset the map's TTL
1479 * return $lruCache->toArray();
1480 * },
1482 * // Once map is > 1 sec old, consider refreshing
1483 * 'ageNew' => 1,
1484 * // Update within 5 seconds after "ageNew" given a 1hz cache check rate
1485 * 'hotTTR' => 5,
1486 * // Avoid querying cache servers multiple times in a request; this also means
1487 * // that a request can only alter the value of any given constraint key once
1488 * 'pcTTL' => WANObjectCache::TTL_PROC_LONG
1490 * );
1491 * $tolerability = isset( $catSituationTolerabilityCache[$scenarioKey] )
1492 * ? $catSituationTolerabilityCache[$scenarioKey]
1493 * : $this->checkScenarioTolerability( $constraintId, $situation );
1494 * @endcode
1496 * @see WANObjectCache::get()
1497 * @see WANObjectCache::set()
1499 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1500 * @param int $ttl Nominal seconds-to-live for newly computed values. Special values are:
1501 * - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
1502 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
1503 * @param callable $callback Value generation function
1504 * @param array $opts Options map:
1505 * - checkKeys: List of "check" keys. The key at $key will be seen as stale when either
1506 * touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This
1507 * is useful if thousands or millions of keys depend on the same entity. The entity can
1508 * simply have its "check" key updated whenever the entity is modified.
1509 * Default: [].
1510 * - graceTTL: If the key is stale due to a purge (by "checkKeys" or "touchedCallback")
1511 * less than this many seconds ago, consider reusing the stale value. The odds of a
1512 * refresh become more likely over time, becoming certain once the grace period is
1513 * reached. This can reduce traffic spikes when millions of keys are compared to the
1514 * same "check" key and touchCheckKey() or resetCheckKey() is called on that "check" key.
1515 * This option is not useful for avoiding traffic spikes in the case of the key simply
1516 * expiring on account of its TTL (use "lowTTL" instead).
1517 * Default: WANObjectCache::GRACE_TTL_NONE.
1518 * - lockTSE: If the value is stale and the "time since expiry" (TSE) is less than the given
1519 * number of seconds ago, then reuse the stale value if another such thread is already
1520 * regenerating the value. The TSE of the key is influenced by purges (e.g. via delete(),
1521 * "checkKeys", "touchedCallback"), and various other options (e.g. "staleTTL"). A low
1522 * enough TSE is assumed to indicate a high enough key access rate to justify stampede
1523 * avoidance. Note that no cache value exists after deletion, expiration, or eviction
1524 * at the storage-layer; to prevent stampedes during these cases, use "busyValue".
1525 * Default: WANObjectCache::TSE_NONE.
1526 * - busyValue: Specify a placeholder value to use when no value exists and another thread
1527 * is currently regenerating it. This assures that cache stampedes cannot happen if the
1528 * value falls out of cache. This also mitigates stampedes when value regeneration
1529 * becomes very slow (greater than $ttl/"lowTTL"). If this is a closure, then it will
1530 * be invoked to get the placeholder when needed.
1531 * Default: null.
1532 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
1533 * network I/O when a key is read several times. This will not cache when the callback
1534 * returns false, however. Note that any purges will not be seen while process cached;
1535 * since the callback should use replica DBs and they may be lagged or have snapshot
1536 * isolation anyway, this should not typically matter.
1537 * Default: WANObjectCache::TTL_UNCACHEABLE.
1538 * - pcGroup: Process cache group to use instead of the primary one. If set, this must be
1539 * of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
1540 * large values, small yet numerous values, or some values with a high cost of eviction.
1541 * It is generally preferable to use a class constant when setting this value.
1542 * This has no effect unless pcTTL is used.
1543 * Default: WANObjectCache::PC_PRIMARY.
1544 * - version: Integer version number. This lets callers make breaking changes to the format
1545 * of cached values without causing problems for sites that use non-instantaneous code
1546 * deployments. Old and new code will recognize incompatible versions and purges from
1547 * both old and new code will been seen by each other. When this method encounters an
1548 * incompatibly versioned value at the provided key, a "variant key" will be used for
1549 * reading from and saving to cache. The variant key is specific to the key and version
1550 * number provided to this method. If the variant key value is older than that of the
1551 * provided key, or the provided key is non-existant, then the variant key will be seen
1552 * as non-existant. Therefore, delete() calls purge the provided key's variant keys.
1553 * The "checkKeys" and "touchedCallback" options still apply to variant keys as usual.
1554 * Avoid storing class objects, as this reduces compatibility (due to serialization).
1555 * Default: null.
1556 * - minAsOf: Reject values if they were generated before this UNIX timestamp.
1557 * This is useful if the source of a key is suspected of having possibly changed
1558 * recently, and the caller wants any such changes to be reflected.
1559 * Default: WANObjectCache::MIN_TIMESTAMP_NONE.
1560 * - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per
1561 * second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this
1562 * TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old.
1563 * This uses randomization to avoid triggering cache stampedes. The TTR is useful at
1564 * reducing the impact of missed cache purges, since the effect of a heavily referenced
1565 * key being stale is worse than that of a rarely referenced key. Unlike simply lowering
1566 * $ttl, seldomly used keys are largely unaffected by this option, which makes it
1567 * possible to have a high hit rate for the "long-tail" of less-used keys.
1568 * Default: WANObjectCache::HOT_TTR.
1569 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
1570 * than this. It becomes more likely over time, becoming certain once the key is expired.
1571 * This helps avoid cache stampedes that might be triggered due to the key expiring.
1572 * Default: WANObjectCache::LOW_TTL.
1573 * - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
1574 * Default: WANObjectCache::AGE_NEW.
1575 * - staleTTL: Seconds to keep the key around if it is stale. This means that on cache
1576 * miss the callback may get $oldValue/$oldAsOf values for keys that have already been
1577 * expired for this specified time. This is useful if adaptiveTTL() is used on the old
1578 * value's as-of time when it is verified as still being correct.
1579 * Default: WANObjectCache::STALE_TTL_NONE
1580 * - touchedCallback: A callback that takes the current value and returns a UNIX timestamp
1581 * indicating the last time a dynamic dependency changed. Null can be returned if there
1582 * are no relevant dependency changes to check. This can be used to check against things
1583 * like last-modified times of files or DB timestamp fields. This should generally not be
1584 * used for small and easily queried values in a DB if the callback itself ends up doing
1585 * a similarly expensive DB query to check a timestamp. Usages of this option makes the
1586 * most sense for values that are moderately to highly expensive to regenerate and easy
1587 * to query for dependency timestamps. The use of "pcTTL" reduces timestamp queries.
1588 * Default: null.
1589 * @param array $cbParams Custom field/value map to pass to the callback (since 1.35)
1590 * @phpcs:ignore Generic.Files.LineLength
1591 * @phan-param array{checkKeys?:string[],graceTTL?:int,lockTSE?:int,busyValue?:mixed,pcTTL?:int,pcGroup?:string,version?:int,minAsOf?:float|int,hotTTR?:int,lowTTL?:int,ageNew?:int,staleTTL?:int,touchedCallback?:callable} $opts
1592 * @return mixed Value found or written to the key
1593 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
1594 * @note Options added in 1.31: staleTTL, graceTTL
1595 * @note Options added in 1.33: touchedCallback
1596 * @note Callable type hints are not used to avoid class-autoloading
1598 final public function getWithSetCallback(
1599 $key, $ttl, $callback, array $opts = [], array $cbParams = []
1601 $version = $opts['version'] ?? null;
1602 $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
1603 $pCache = ( $pcTTL >= 0 )
1604 ? $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY )
1605 : null;
1607 // Use the process cache if requested as long as no outer cache callback is running.
1608 // Nested callback process cache use is not lag-safe with regard to HOLDOFF_TTL since
1609 // process cached values are more lagged than persistent ones as they are not purged.
1610 if ( $pCache && $this->callbackDepth == 0 ) {
1611 $cached = $pCache->get( $key, $pcTTL, false );
1612 if ( $cached !== false ) {
1613 $this->logger->debug( "getWithSetCallback($key): process cache hit" );
1614 return $cached;
1618 [ $value, $valueVersion, $curAsOf ] = $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams );
1619 if ( $valueVersion !== $version ) {
1620 // Current value has a different version; use the variant key for this version.
1621 // Regenerate the variant value if it is not newer than the main value at $key
1622 // so that purges to the main key propagate to the variant value.
1623 $this->logger->debug( "getWithSetCallback($key): using variant key" );
1624 [ $value ] = $this->fetchOrRegenerate(
1625 $this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), (string)$version ),
1626 $ttl,
1627 $callback,
1628 [ 'version' => null, 'minAsOf' => $curAsOf ] + $opts,
1629 $cbParams
1633 // Update the process cache if enabled
1634 if ( $pCache && $value !== false ) {
1635 $pCache->set( $key, $value );
1638 return $value;
1642 * Do the actual I/O for getWithSetCallback() when needed
1644 * @see WANObjectCache::getWithSetCallback()
1646 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1647 * @param int $ttl
1648 * @param callable $callback
1649 * @param array $opts
1650 * @param array $cbParams
1651 * @return array Ordered list of the following:
1652 * - Cached or regenerated value
1653 * - Cached or regenerated value version number or null if not versioned
1654 * - Timestamp of the current cached value at the key or null if there is no value
1655 * @note Callable type hints are not used to avoid class-autoloading
1657 private function fetchOrRegenerate( $key, $ttl, $callback, array $opts, array $cbParams ) {
1658 $checkKeys = $opts['checkKeys'] ?? [];
1659 $graceTTL = $opts['graceTTL'] ?? self::GRACE_TTL_NONE;
1660 $minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
1661 $hotTTR = $opts['hotTTR'] ?? self::HOT_TTR;
1662 $lowTTL = $opts['lowTTL'] ?? min( self::LOW_TTL, $ttl );
1663 $ageNew = $opts['ageNew'] ?? self::AGE_NEW;
1664 $touchedCb = $opts['touchedCallback'] ?? null;
1665 $startTime = $this->getCurrentTime();
1667 $keygroup = $this->determineKeyGroupForStats( $key );
1669 // Get the current key value and its metadata
1670 $curState = $this->fetchKeys( [ $key ], $checkKeys, $startTime, $touchedCb )[$key];
1671 $curValue = $curState[self::RES_VALUE];
1673 // Use the cached value if it exists and is not due for synchronous regeneration
1674 if ( $this->isAcceptablyFreshValue( $curState, $graceTTL, $minAsOf ) ) {
1675 if ( !$this->isLotteryRefreshDue( $curState, $lowTTL, $ageNew, $hotTTR, $startTime ) ) {
1676 $this->stats->getTiming( 'wanobjectcache_getwithset_seconds' )
1677 ->setLabel( 'keygroup', $keygroup )
1678 ->setLabel( 'result', 'hit' )
1679 ->setLabel( 'reason', 'good' )
1680 ->copyToStatsdAt( "wanobjectcache.$keygroup.hit.good" )
1681 ->observe( 1e3 * ( $this->getCurrentTime() - $startTime ) );
1683 return [ $curValue, $curState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1684 } elseif ( $this->scheduleAsyncRefresh( $key, $ttl, $callback, $opts, $cbParams ) ) {
1685 $this->logger->debug( "fetchOrRegenerate($key): hit with async refresh" );
1687 $this->stats->getTiming( 'wanobjectcache_getwithset_seconds' )
1688 ->setLabel( 'keygroup', $keygroup )
1689 ->setLabel( 'result', 'hit' )
1690 ->setLabel( 'reason', 'refresh' )
1691 ->copyToStatsdAt( "wanobjectcache.$keygroup.hit.refresh" )
1692 ->observe( 1e3 * ( $this->getCurrentTime() - $startTime ) );
1694 return [ $curValue, $curState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1695 } else {
1696 $this->logger->debug( "fetchOrRegenerate($key): hit with sync refresh" );
1700 $isKeyTombstoned = ( $curState[self::RES_TOMB_AS_OF] !== null );
1701 // Use the interim key as a temporary alternative if the key is tombstoned
1702 if ( $isKeyTombstoned ) {
1703 $volState = $this->getInterimValue( $key, $minAsOf, $startTime, $touchedCb );
1704 $volValue = $volState[self::RES_VALUE];
1705 } else {
1706 $volState = $curState;
1707 $volValue = $curValue;
1710 // During the volatile "hold-off" period that follows a purge of the key, the value
1711 // will be regenerated many times if frequently accessed. This is done to mitigate
1712 // the effects of backend replication lag as soon as possible. However, throttle the
1713 // overhead of locking and regeneration by reusing values recently written to cache
1714 // tens of milliseconds ago. Verify the "as of" time against the last purge event.
1715 $lastPurgeTime = max(
1716 // RES_TOUCH_AS_OF depends on the value (possibly from the interim key)
1717 $volState[self::RES_TOUCH_AS_OF],
1718 $curState[self::RES_TOMB_AS_OF],
1719 $curState[self::RES_CHECK_AS_OF]
1721 $safeMinAsOf = max( $minAsOf, $lastPurgeTime + self::TINY_POSITIVE );
1722 if ( $this->isExtremelyNewValue( $volState, $safeMinAsOf, $startTime ) ) {
1723 $this->logger->debug( "fetchOrRegenerate($key): volatile hit" );
1725 $this->stats->getTiming( 'wanobjectcache_getwithset_seconds' )
1726 ->setLabel( 'keygroup', $keygroup )
1727 ->setLabel( 'result', 'hit' )
1728 ->setLabel( 'reason', 'volatile' )
1729 ->copyToStatsdAt( "wanobjectcache.$keygroup.hit.volatile" )
1730 ->observe( 1e3 * ( $this->getCurrentTime() - $startTime ) );
1732 return [ $volValue, $volState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1735 $lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
1736 $busyValue = $opts['busyValue'] ?? null;
1737 $staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
1738 $segmentable = $opts['segmentable'] ?? false;
1739 $version = $opts['version'] ?? null;
1741 // Determine whether one thread per datacenter should handle regeneration at a time
1742 $useRegenerationLock =
1743 // Note that since tombstones no-op set(), $lockTSE and $curTTL cannot be used to
1744 // deduce the key hotness because |$curTTL| will always keep increasing until the
1745 // tombstone expires or is overwritten by a new tombstone. Also, even if $lockTSE
1746 // is not set, constant regeneration of a key for the tombstone lifetime might be
1747 // very expensive. Assume tombstoned keys are possibly hot in order to reduce
1748 // the risk of high regeneration load after the delete() method is called.
1749 $isKeyTombstoned ||
1750 // Assume a key is hot if requested soon ($lockTSE seconds) after purge.
1751 // This avoids stampedes when timestamps from $checkKeys/$touchedCb bump.
1753 $curState[self::RES_CUR_TTL] !== null &&
1754 $curState[self::RES_CUR_TTL] <= 0 &&
1755 abs( $curState[self::RES_CUR_TTL] ) <= $lockTSE
1756 ) ||
1757 // Assume a key is hot if there is no value and a busy fallback is given.
1758 // This avoids stampedes on eviction or preemptive regeneration taking too long.
1759 ( $busyValue !== null && $volValue === false );
1761 // If a regeneration lock is required, threads that do not get the lock will try to use
1762 // the stale value, the interim value, or the $busyValue placeholder, in that order. If
1763 // none of those are set then all threads will bypass the lock and regenerate the value.
1764 $hasLock = $useRegenerationLock && $this->claimStampedeLock( $key );
1765 if ( $useRegenerationLock && !$hasLock ) {
1766 // Determine if there is stale or volatile cached value that is still usable
1767 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
1768 if ( $this->isValid( $volValue, $volState[self::RES_AS_OF], $minAsOf ) ) {
1769 $this->logger->debug( "fetchOrRegenerate($key): returning stale value" );
1771 $this->stats->getTiming( 'wanobjectcache_getwithset_seconds' )
1772 ->setLabel( 'keygroup', $keygroup )
1773 ->setLabel( 'result', 'hit' )
1774 ->setLabel( 'reason', 'stale' )
1775 ->copyToStatsdAt( "wanobjectcache.$keygroup.hit.stale" )
1776 ->observe( 1e3 * ( $this->getCurrentTime() - $startTime ) );
1778 return [ $volValue, $volState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1779 } elseif ( $busyValue !== null ) {
1780 $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1781 $this->logger->debug( "fetchOrRegenerate($key): busy $miss" );
1783 $this->stats->getTiming( 'wanobjectcache_getwithset_seconds' )
1784 ->setLabel( 'keygroup', $keygroup )
1785 ->setLabel( 'result', $miss )
1786 ->setLabel( 'reason', 'busy' )
1787 ->copyToStatsdAt( "wanobjectcache.$keygroup.$miss.busy" )
1788 ->observe( 1e3 * ( $this->getCurrentTime() - $startTime ) );
1790 $placeholderValue = $this->resolveBusyValue( $busyValue );
1792 return [ $placeholderValue, $version, $curState[self::RES_AS_OF] ];
1796 // Generate the new value given any prior value with a matching version
1797 $setOpts = [];
1798 $preCallbackTime = $this->getCurrentTime();
1799 ++$this->callbackDepth;
1800 // https://github.com/phan/phan/issues/4419
1801 $value = null;
1802 try {
1803 $value = $callback(
1804 ( $curState[self::RES_VERSION] === $version ) ? $curValue : false,
1805 $ttl,
1806 $setOpts,
1807 ( $curState[self::RES_VERSION] === $version ) ? $curState[self::RES_AS_OF] : null,
1808 $cbParams
1810 } finally {
1811 --$this->callbackDepth;
1813 $postCallbackTime = $this->getCurrentTime();
1815 // How long it took to generate the value
1816 $walltime = max( $postCallbackTime - $preCallbackTime, 0.0 );
1818 $this->stats->getTiming( 'wanobjectcache_regen_seconds' )
1819 ->setLabel( 'keygroup', $keygroup )
1820 ->copyToStatsdAt( "wanobjectcache.$keygroup.regen_walltime" )
1821 ->observe( 1e3 * $walltime );
1823 // Attempt to save the newly generated value if applicable
1824 if (
1825 // Callback yielded a cacheable value
1826 ( $value !== false && $ttl >= 0 ) &&
1827 // Current thread was not raced out of a regeneration lock or key is tombstoned
1828 ( !$useRegenerationLock || $hasLock || $isKeyTombstoned )
1830 // If the key is write-holed then use the (volatile) interim key as an alternative
1831 if ( $isKeyTombstoned ) {
1832 $this->setInterimValue(
1833 $key,
1834 $value,
1835 $lockTSE,
1836 $version,
1837 $segmentable
1839 } else {
1840 $this->setMainValue(
1841 $key,
1842 $value,
1843 $ttl,
1844 $version,
1845 $walltime,
1846 // @phan-suppress-next-line PhanCoalescingAlwaysNull
1847 $setOpts['lag'] ?? 0,
1848 // @phan-suppress-next-line PhanCoalescingAlwaysNull
1849 $setOpts['since'] ?? $preCallbackTime,
1850 // @phan-suppress-next-line PhanCoalescingAlwaysNull
1851 $setOpts['pending'] ?? false,
1852 $lockTSE,
1853 $staleTTL,
1854 $segmentable,
1855 ( $curValue === false )
1860 $this->yieldStampedeLock( $key, $hasLock );
1862 $miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1863 $this->logger->debug( "fetchOrRegenerate($key): $miss, new value computed" );
1865 $this->stats->getTiming( 'wanobjectcache_getwithset_seconds' )
1866 ->setLabel( 'keygroup', $keygroup )
1867 ->setLabel( 'result', $miss )
1868 ->setLabel( 'reason', 'compute' )
1869 ->copyToStatsdAt( "wanobjectcache.$keygroup.$miss.compute" )
1870 ->observe( 1e3 * ( $this->getCurrentTime() - $startTime ) );
1872 return [ $value, $version, $curState[self::RES_AS_OF] ];
1876 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1877 * @return bool Success
1879 private function claimStampedeLock( $key ) {
1880 $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX );
1881 // Note that locking is not bypassed due to I/O errors; this avoids stampedes
1882 return $this->cache->add( $checkSisterKey, 1, self::LOCK_TTL );
1886 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1887 * @param bool $hasLock
1889 private function yieldStampedeLock( $key, $hasLock ) {
1890 if ( $hasLock ) {
1891 $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX );
1892 $this->cache->delete( $checkSisterKey, $this->cache::WRITE_BACKGROUND );
1897 * Get sister keys that should be collocated with their corresponding base cache keys
1899 * The key will bear the WANCache prefix and use the configured coalescing scheme
1901 * @param string[] $baseKeys Cache keys made with makeKey()/makeGlobalKey()
1902 * @param string $type Consistent hashing agnostic suffix character matching [a-zA-Z]
1903 * @param string|null $route Routing prefix (optional)
1904 * @return string[] Order-corresponding list of sister keys
1906 private function makeSisterKeys( array $baseKeys, string $type, ?string $route = null ) {
1907 $sisterKeys = [];
1908 foreach ( $baseKeys as $baseKey ) {
1909 $sisterKeys[] = $this->makeSisterKey( $baseKey, $type, $route );
1912 return $sisterKeys;
1916 * Get a sister key that should be collocated with a base cache key
1918 * The keys will bear the WANCache prefix and use the configured coalescing scheme
1920 * @param string $baseKey Cache key made with makeKey()/makeGlobalKey()
1921 * @param string $typeChar Consistent hashing agnostic suffix character matching [a-zA-Z]
1922 * @param string|null $route Routing prefix (optional)
1923 * @return string Sister key
1925 private function makeSisterKey( string $baseKey, string $typeChar, ?string $route = null ) {
1926 if ( $this->coalesceScheme === self::SCHEME_HASH_STOP ) {
1927 // Key style: "WANCache:<base key>|#|<character>"
1928 $sisterKey = 'WANCache:' . $baseKey . '|#|' . $typeChar;
1929 } else {
1930 // Key style: "WANCache:{<base key>}:<character>"
1931 $sisterKey = 'WANCache:{' . $baseKey . '}:' . $typeChar;
1934 if ( $route !== null ) {
1935 $sisterKey = $this->prependRoute( $sisterKey, $route );
1938 return $sisterKey;
1942 * Check if a key value is non-false, new enough, and has an "as of" time almost equal to now
1944 * If the value was just written to cache, and it did not take an unusually long time to
1945 * generate, then it is probably not worth regenerating yet. For example, replica databases
1946 * might still return lagged pre-purge values anyway.
1948 * @param array $res Current value WANObjectCache::RES_* data map
1949 * @param float $minAsOf Minimum acceptable value "as of" UNIX timestamp
1950 * @param float $now Current UNIX timestamp
1951 * @return bool Whether the age of a volatile value is negligible
1953 private function isExtremelyNewValue( $res, $minAsOf, $now ) {
1954 if ( $res[self::RES_VALUE] === false || $res[self::RES_AS_OF] < $minAsOf ) {
1955 return false;
1958 $age = $now - $res[self::RES_AS_OF];
1960 return ( $age < mt_rand( self::RECENT_SET_LOW_MS, self::RECENT_SET_HIGH_MS ) / 1e3 );
1964 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1965 * @param float $minAsOf Minimum acceptable value "as of" UNIX timestamp
1966 * @param float $now Fetch time to determine "age" metadata
1967 * @param callable|null $touchedCb Function to find the max "dependency touched" UNIX timestamp
1968 * @return array<int,mixed> Result map/n-tuple from unwrap()
1969 * @phan-return array{0:mixed,1:mixed,2:?float,3:?int,4:?float,5:?float,6:?float,7:?float}
1970 * @note Callable type hints are not used to avoid class-autoloading
1972 private function getInterimValue( $key, $minAsOf, $now, $touchedCb ) {
1973 if ( $this->useInterimHoldOffCaching ) {
1974 $interimSisterKey = $this->makeSisterKey( $key, self::TYPE_INTERIM );
1975 $wrapped = $this->cache->get( $interimSisterKey );
1976 $res = $this->unwrap( $wrapped, $now );
1977 if ( $res[self::RES_VALUE] !== false && $res[self::RES_AS_OF] >= $minAsOf ) {
1978 if ( $touchedCb !== null ) {
1979 // Update "last purge time" since the $touchedCb timestamp depends on $value
1980 // Get the new "touched timestamp", accounting for callback-checked dependencies
1981 $res[self::RES_TOUCH_AS_OF] = max(
1982 $touchedCb( $res[self::RES_VALUE] ),
1983 $res[self::RES_TOUCH_AS_OF]
1987 return $res;
1991 return $this->unwrap( false, $now );
1995 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1996 * @param mixed $value
1997 * @param int|float $ttl
1998 * @param int|null $version Value version number
1999 * @param bool $segmentable
2000 * @return bool Success
2002 private function setInterimValue(
2003 $key,
2004 $value,
2005 $ttl,
2006 ?int $version,
2007 bool $segmentable
2009 $now = $this->getCurrentTime();
2010 $ttl = max( self::INTERIM_KEY_TTL, (int)$ttl );
2012 // Wrap that value with time/TTL/version metadata
2013 $wrapped = $this->wrap( $value, $ttl, $version, $now );
2015 $flags = $this->cache::WRITE_BACKGROUND;
2016 if ( $segmentable ) {
2017 $flags |= $this->cache::WRITE_ALLOW_SEGMENTS;
2020 return $this->cache->set(
2021 $this->makeSisterKey( $key, self::TYPE_INTERIM ),
2022 $wrapped,
2023 $ttl,
2024 $flags
2029 * @param mixed $busyValue
2030 * @return mixed
2032 private function resolveBusyValue( $busyValue ) {
2033 return ( $busyValue instanceof Closure ) ? $busyValue() : $busyValue;
2037 * Method to fetch multiple cache keys at once with regeneration
2039 * This works the same as getWithSetCallback() except:
2040 * - a) The $keys argument must be the result of WANObjectCache::makeMultiKeys()
2041 * - b) The $callback argument expects a function that returns an entity value, using
2042 * boolean "false" if it does not exist. The callback takes the following arguments:
2043 * - $id: ID of the entity to query
2044 * - $oldValue: prior cache value or false if none was present
2045 * - &$ttl: reference to the TTL to be assigned to the new value (alterable)
2046 * - &$setOpts: reference to the new value set() options (alterable)
2047 * - $oldAsOf: generation UNIX timestamp of $oldValue or null if not present
2048 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
2050 * @see WANObjectCache::getWithSetCallback()
2051 * @see WANObjectCache::getMultiWithUnionSetCallback()
2053 * Example usage:
2054 * @code
2055 * $rows = $cache->getMultiWithSetCallback(
2056 * // Map of cache keys to entity IDs
2057 * $cache->makeMultiKeys(
2058 * $this->fileVersionIds(),
2059 * function ( $id, $cache ) {
2060 * return $cache->makeKey( 'file-version', $id );
2062 * ),
2063 * // Time-to-live (in seconds)
2064 * $cache::TTL_DAY,
2065 * // Function that derives the new key value
2066 * function ( $id, $oldValue, &$ttl, array &$setOpts ) {
2067 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
2068 * // Account for any snapshot/replica DB lag
2069 * $setOpts += Database::getCacheSetOptions( $dbr );
2071 * // Load the row for this file
2072 * $queryInfo = File::getQueryInfo();
2073 * $row = $dbr->selectRow(
2074 * $queryInfo['tables'],
2075 * $queryInfo['fields'],
2076 * [ 'id' => $id ],
2077 * __METHOD__,
2078 * [],
2079 * $queryInfo['joins']
2080 * );
2082 * return $row ? (array)$row : false;
2083 * },
2085 * // Process cache for 30 seconds
2086 * 'pcTTL' => 30,
2087 * // Use a dedicated 500 item cache (initialized on-the-fly)
2088 * 'pcGroup' => 'file-versions:500'
2090 * );
2091 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
2092 * @endcode
2094 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
2095 * @param int $ttl Seconds to live for key updates
2096 * @param callable $callback Callback that yields entity generation callbacks
2097 * @param array $opts Options map similar to that of getWithSetCallback()
2098 * @return mixed[] Map of (cache key => value) in the same order as $keyedIds
2099 * @since 1.28
2101 final public function getMultiWithSetCallback(
2102 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
2104 // Batch load required keys into the in-process warmup cache
2105 $this->warmupCache = $this->fetchWrappedValuesForWarmupCache(
2106 $this->getNonProcessCachedMultiKeys( $keyedIds, $opts ),
2107 $opts['checkKeys'] ?? []
2109 $this->warmupKeyMisses = 0;
2111 // The required callback signature includes $id as the first argument for convenience
2112 // to distinguish different items. To reuse the code in getWithSetCallback(), wrap the
2113 // callback with a proxy callback that has the standard getWithSetCallback() signature.
2114 // This is defined only once per batch to avoid closure creation overhead.
2115 $proxyCb = static function ( $oldValue, &$ttl, &$setOpts, $oldAsOf, $params )
2116 use ( $callback )
2118 return $callback( $params['id'], $oldValue, $ttl, $setOpts, $oldAsOf );
2121 // Get the order-preserved result map using the warm-up cache
2122 $values = [];
2123 foreach ( $keyedIds as $key => $id ) {
2124 $values[$key] = $this->getWithSetCallback(
2125 $key,
2126 $ttl,
2127 $proxyCb,
2128 $opts,
2129 [ 'id' => $id ]
2133 $this->warmupCache = [];
2135 return $values;
2139 * Method to fetch/regenerate multiple cache keys at once
2141 * This works the same as getWithSetCallback() except:
2142 * - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
2143 * - b) The $callback argument expects a function that returns a map of (ID => new value),
2144 * using boolean "false" for entities that could not be found, for all entity IDs in
2145 * $ids. The callback takes the following arguments:
2146 * - $ids: list of entity IDs that require value generation
2147 * - &$ttls: reference to the (entity ID => new TTL) map (alterable)
2148 * - &$setOpts: reference to the new value set() options (alterable)
2149 * - c) The return value is a map of (cache key => value) in the order of $keyedIds
2150 * - d) The "lockTSE" and "busyValue" options are ignored
2152 * @see WANObjectCache::getWithSetCallback()
2153 * @see WANObjectCache::getMultiWithSetCallback()
2155 * Example usage:
2156 * @code
2157 * $rows = $cache->getMultiWithUnionSetCallback(
2158 * // Map of cache keys to entity IDs
2159 * $cache->makeMultiKeys(
2160 * $this->fileVersionIds(),
2161 * function ( $id ) use ( $cache ) {
2162 * return $cache->makeKey( 'file-version', $id );
2164 * ),
2165 * // Time-to-live (in seconds)
2166 * $cache::TTL_DAY,
2167 * // Function that derives the new key value
2168 * function ( array $ids, array &$ttls, array &$setOpts ) {
2169 * $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
2170 * // Account for any snapshot/replica DB lag
2171 * $setOpts += Database::getCacheSetOptions( $dbr );
2173 * // Load the rows for these files
2174 * $rows = array_fill_keys( $ids, false );
2175 * $queryInfo = File::getQueryInfo();
2176 * $res = $dbr->select(
2177 * $queryInfo['tables'],
2178 * $queryInfo['fields'],
2179 * [ 'id' => $ids ],
2180 * __METHOD__,
2181 * [],
2182 * $queryInfo['joins']
2183 * );
2184 * foreach ( $res as $row ) {
2185 * $rows[$row->id] = $row;
2186 * $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
2187 * $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
2190 * return $rows;
2191 * },
2193 * );
2194 * $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
2195 * @endcode
2197 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
2198 * @param int $ttl Seconds to live for key updates
2199 * @param callable $callback Callback that yields entity generation callbacks
2200 * @param array $opts Options map similar to that of getWithSetCallback()
2201 * @return mixed[] Map of (cache key => value) in the same order as $keyedIds
2202 * @since 1.30
2204 final public function getMultiWithUnionSetCallback(
2205 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
2207 $checkKeys = $opts['checkKeys'] ?? [];
2208 $minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
2210 // unset incompatible keys
2211 unset( $opts['lockTSE'] );
2212 unset( $opts['busyValue'] );
2214 // Batch load required keys into the in-process warmup cache
2215 $keysByIdGet = $this->getNonProcessCachedMultiKeys( $keyedIds, $opts );
2216 $this->warmupCache = $this->fetchWrappedValuesForWarmupCache( $keysByIdGet, $checkKeys );
2217 $this->warmupKeyMisses = 0;
2219 // IDs of entities known to be in need of generation
2220 $idsRegen = [];
2222 // Find out which keys are missing/deleted/stale
2223 $now = $this->getCurrentTime();
2224 $resByKey = $this->fetchKeys( $keysByIdGet, $checkKeys, $now );
2225 foreach ( $keysByIdGet as $id => $key ) {
2226 $res = $resByKey[$key];
2227 if (
2228 $res[self::RES_VALUE] === false ||
2229 $res[self::RES_CUR_TTL] < 0 ||
2230 $res[self::RES_AS_OF] < $minAsOf
2232 $idsRegen[] = $id;
2236 // Run the callback to populate the generation value map for all required IDs
2237 $newSetOpts = [];
2238 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
2239 $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
2241 $method = __METHOD__;
2242 // The required callback signature includes $id as the first argument for convenience
2243 // to distinguish different items. To reuse the code in getWithSetCallback(), wrap the
2244 // callback with a proxy callback that has the standard getWithSetCallback() signature.
2245 // This is defined only once per batch to avoid closure creation overhead.
2246 $proxyCb = function ( $oldValue, &$ttl, &$setOpts, $oldAsOf, $params )
2247 use ( $callback, $newValsById, $newTTLsById, $newSetOpts, $method )
2249 $id = $params['id'];
2251 if ( array_key_exists( $id, $newValsById ) ) {
2252 // Value was already regenerated as expected, so use the value in $newValsById
2253 $newValue = $newValsById[$id];
2254 $ttl = $newTTLsById[$id];
2255 $setOpts = $newSetOpts;
2256 } else {
2257 // Pre-emptive/popularity refresh and version mismatch cases are not detected
2258 // above and thus $newValsById has no entry. Run $callback on this single entity.
2259 $ttls = [ $id => $ttl ];
2260 $result = $callback( [ $id ], $ttls, $setOpts );
2261 if ( !isset( $result[$id] ) ) {
2262 // T303092
2263 $this->logger->warning(
2264 $method . ' failed due to {id} not set in result {result}', [
2265 'id' => $id,
2266 'result' => json_encode( $result )
2267 ] );
2269 $newValue = $result[$id];
2270 $ttl = $ttls[$id];
2273 return $newValue;
2276 // Get the order-preserved result map using the warm-up cache
2277 $values = [];
2278 foreach ( $keyedIds as $key => $id ) {
2279 $values[$key] = $this->getWithSetCallback(
2280 $key,
2281 $ttl,
2282 $proxyCb,
2283 $opts,
2284 [ 'id' => $id ]
2288 $this->warmupCache = [];
2290 return $values;
2294 * @see BagOStuff::makeGlobalKey()
2295 * @since 1.27
2296 * @param string $keygroup Key group component, should be under 48 characters.
2297 * @param string|int ...$components Additional, ordered, key components for entity IDs
2298 * @return string Colon-separated, keyspace-prepended, ordered list of encoded components
2300 public function makeGlobalKey( $keygroup, ...$components ) {
2301 return $this->cache->makeGlobalKey( $keygroup, ...$components );
2305 * @see BagOStuff::makeKey()
2306 * @since 1.27
2307 * @param string $keygroup Key group component, should be under 48 characters.
2308 * @param string|int ...$components Additional, ordered, key components for entity IDs
2309 * @return string Colon-separated, keyspace-prepended, ordered list of encoded components
2311 public function makeKey( $keygroup, ...$components ) {
2312 return $this->cache->makeKey( $keygroup, ...$components );
2316 * Hash a possibly long string into a suitable component for makeKey()/makeGlobalKey()
2318 * @param string $component A raw component used in building a cache key
2319 * @return string 64 character HMAC using a stable secret for public collision resistance
2320 * @since 1.34
2322 public function hash256( $component ) {
2323 return hash_hmac( 'sha256', $component, $this->secret );
2327 * Get an iterator of (cache key => entity ID) for a list of entity IDs
2329 * The $callback argument expects a function that returns the key for an entity ID via
2330 * makeKey()/makeGlobalKey(). There should be no network nor filesystem I/O used in the
2331 * callback. The entity ID/key mapping must be 1:1 or an exception will be thrown. Use
2332 * the hash256() method for any hashing. The callback takes the following arguments:
2333 * - $id: An entity ID
2334 * - $cache: This WANObjectCache instance
2336 * Example usage for the default keyspace:
2337 * @code
2338 * $keyedIds = $cache->makeMultiKeys(
2339 * $modules,
2340 * function ( $module, $cache ) {
2341 * return $cache->makeKey( 'example-module', $module );
2343 * );
2344 * @endcode
2346 * Example usage for mixed default and global keyspace:
2347 * @code
2348 * $keyedIds = $cache->makeMultiKeys(
2349 * $filters,
2350 * function ( $filter, $cache ) {
2351 * return self::isCentral( $filter )
2352 * ? $cache->makeGlobalKey( 'example-filter', $filter )
2353 * : $cache->makeKey( 'example-filter', $filter )
2355 * );
2356 * @endcode
2358 * Example usage with hashing:
2359 * @code
2360 * $keyedIds = $cache->makeMultiKeys(
2361 * $urls,
2362 * function ( $url, $cache ) {
2363 * return $cache->makeKey( 'example-url', $cache->hash256( $url ) );
2365 * );
2366 * @endcode
2368 * @see WANObjectCache::makeKey()
2369 * @see WANObjectCache::makeGlobalKey()
2370 * @see WANObjectCache::hash256()
2372 * @param string[]|int[] $ids List of entity IDs
2373 * @param callable $keyCallback Function returning makeKey()/makeGlobalKey() on the input ID
2374 * @return ArrayIterator Iterator of (cache key => ID); order of $ids is preserved
2375 * @since 1.28
2377 final public function makeMultiKeys( array $ids, $keyCallback ) {
2378 $idByKey = [];
2379 foreach ( $ids as $id ) {
2380 // Discourage triggering of automatic makeKey() hashing in some backends
2381 if ( strlen( $id ) > 64 ) {
2382 $this->logger->warning( __METHOD__ . ": long ID '$id'; use hash256()" );
2384 $key = $keyCallback( $id, $this );
2385 // Edge case: ignore key collisions due to duplicate $ids like "42" and 42
2386 if ( !isset( $idByKey[$key] ) ) {
2387 $idByKey[$key] = $id;
2388 } elseif ( (string)$id !== (string)$idByKey[$key] ) {
2389 throw new UnexpectedValueException(
2390 "Cache key collision; IDs ('$id','{$idByKey[$key]}') map to '$key'"
2395 return new ArrayIterator( $idByKey );
2399 * Get an (ID => value) map from (i) a non-unique list of entity IDs, and (ii) the list
2400 * of corresponding entity values by first appearance of each ID in the entity ID list
2402 * For use with getMultiWithSetCallback() and getMultiWithUnionSetCallback().
2404 * *Only* use this method if the entity ID/key mapping is trivially 1:1 without exception.
2405 * Key generation method must utilize the *full* entity ID in the key (not a hash of it).
2407 * Example usage:
2408 * @code
2409 * $poems = $cache->getMultiWithSetCallback(
2410 * $cache->makeMultiKeys(
2411 * $uuids,
2412 * function ( $uuid ) use ( $cache ) {
2413 * return $cache->makeKey( 'poem', $uuid );
2415 * ),
2416 * $cache::TTL_DAY,
2417 * function ( $uuid ) use ( $url ) {
2418 * return $this->http->run( [ 'method' => 'GET', 'url' => "$url/$uuid" ] );
2420 * );
2421 * $poemsByUUID = $cache->multiRemap( $uuids, $poems );
2422 * @endcode
2424 * @see WANObjectCache::makeMultiKeys()
2425 * @see WANObjectCache::getMultiWithSetCallback()
2426 * @see WANObjectCache::getMultiWithUnionSetCallback()
2428 * @param string[]|int[] $ids Entity ID list makeMultiKeys()
2429 * @param mixed[] $res Result of getMultiWithSetCallback()/getMultiWithUnionSetCallback()
2430 * @return mixed[] Map of (ID => value); order of $ids is preserved
2431 * @since 1.34
2433 final public function multiRemap( array $ids, array $res ) {
2434 if ( count( $ids ) !== count( $res ) ) {
2435 // If makeMultiKeys() is called on a list of non-unique IDs, then the resulting
2436 // ArrayIterator will have less entries due to "first appearance" de-duplication
2437 $ids = array_keys( array_fill_keys( $ids, true ) );
2438 if ( count( $ids ) !== count( $res ) ) {
2439 throw new UnexpectedValueException( "Multi-key result does not match ID list" );
2443 return array_combine( $ids, $res );
2447 * Get a "watch point" token that can be used to get the "last error" to occur after now
2449 * @return int A token that the current error event
2450 * @since 1.38
2452 public function watchErrors() {
2453 return $this->cache->watchErrors();
2457 * Get the "last error" registry
2459 * The method should be invoked by a caller as part of the following pattern:
2460 * - The caller invokes watchErrors() to get a "since token"
2461 * - The caller invokes a sequence of cache operation methods
2462 * - The caller invokes getLastError() with the "since token"
2464 * External callers can also invoke this method as part of the following pattern:
2465 * - The caller invokes clearLastError()
2466 * - The caller invokes a sequence of cache operation methods
2467 * - The caller invokes getLastError()
2469 * @param int $watchPoint Only consider errors from after this "watch point" [optional]
2470 * @return int BagOStuff:ERR_* constant for the "last error" registry
2471 * @note Parameters added in 1.38: $watchPoint
2473 final public function getLastError( $watchPoint = 0 ) {
2474 $code = $this->cache->getLastError( $watchPoint );
2475 switch ( $code ) {
2476 case self::ERR_NONE:
2477 return self::ERR_NONE;
2478 case self::ERR_NO_RESPONSE:
2479 return self::ERR_NO_RESPONSE;
2480 case self::ERR_UNREACHABLE:
2481 return self::ERR_UNREACHABLE;
2482 default:
2483 return self::ERR_UNEXPECTED;
2488 * Clear the "last error" registry
2489 * @deprecated Since 1.38, hard deprecated in 1.43
2491 final public function clearLastError() {
2492 wfDeprecated( __METHOD__, '1.38' );
2493 $this->cache->clearLastError();
2497 * Clear the in-process caches; useful for testing
2499 * @since 1.27
2501 public function clearProcessCache() {
2502 $this->processCaches = [];
2506 * Enable or disable the use of brief caching for tombstoned keys
2508 * When a key is purged via delete(), there normally is a period where caching
2509 * is hold-off limited to an extremely short time. This method will disable that
2510 * caching, forcing the callback to run for any of:
2511 * - WANObjectCache::getWithSetCallback()
2512 * - WANObjectCache::getMultiWithSetCallback()
2513 * - WANObjectCache::getMultiWithUnionSetCallback()
2515 * This is useful when both:
2516 * - a) the database used by the callback is known to be up-to-date enough
2517 * for some particular purpose (e.g. replica DB has applied transaction X)
2518 * - b) the caller needs to exploit that fact, and therefore needs to avoid the
2519 * use of inherently volatile and possibly stale interim keys
2521 * @see WANObjectCache::delete()
2522 * @param bool $enabled Whether to enable interim caching
2523 * @since 1.31
2525 final public function useInterimHoldOffCaching( $enabled ) {
2526 $this->useInterimHoldOffCaching = $enabled;
2530 * @param int $flag ATTR_* class constant
2531 * @return int QOS_* class constant
2532 * @since 1.28
2534 public function getQoS( $flag ) {
2535 return $this->cache->getQoS( $flag );
2539 * Get a TTL that is higher for objects that have not changed recently
2541 * This is useful for keys that get explicit purges and DB or purge relay
2542 * lag is a potential concern (especially how it interacts with CDN cache)
2544 * Example usage:
2545 * @code
2546 * // Last-modified time of page
2547 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
2548 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
2549 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
2550 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
2551 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
2552 * @endcode
2554 * Another use case is when there are no applicable "last modified" fields in the DB,
2555 * and there are too many dependencies for explicit purges to be viable, and the rate of
2556 * change to relevant content is unstable, and it is highly valued to have the cached value
2557 * be as up-to-date as possible.
2559 * Example usage:
2560 * @code
2561 * $query = "<some complex query>";
2562 * $idListFromComplexQuery = $cache->getWithSetCallback(
2563 * $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
2564 * GraphQueryClass::STARTING_TTL,
2565 * function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
2566 * $gdb = $this->getReplicaGraphDbConnection();
2567 * // Account for any snapshot/replica DB lag
2568 * $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
2570 * $newList = iterator_to_array( $gdb->query( $query ) );
2571 * sort( $newList, SORT_NUMERIC ); // normalize
2573 * $minTTL = GraphQueryClass::MIN_TTL;
2574 * $maxTTL = GraphQueryClass::MAX_TTL;
2575 * if ( $oldValue !== false ) {
2576 * // Note that $oldAsOf is the last time this callback ran
2577 * $ttl = ( $newList === $oldValue )
2578 * // No change: cache for 150% of the age of $oldValue
2579 * ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
2580 * // Changed: cache for 50% of the age of $oldValue
2581 * : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
2584 * return $newList;
2585 * },
2587 * // Keep stale values around for doing comparisons for TTL calculations.
2588 * // High values improve long-tail keys hit-rates, though might waste space.
2589 * 'staleTTL' => GraphQueryClass::GRACE_TTL
2591 * );
2592 * @endcode
2594 * @param int|float|string|null $mtime UNIX timestamp; null if none
2595 * @param int $maxTTL Maximum TTL (seconds)
2596 * @param int $minTTL Minimum TTL (seconds); Default: 30
2597 * @param float $factor Value in the range (0,1); Default: .2
2598 * @return int Adaptive TTL
2599 * @since 1.28
2601 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
2602 // handle fractional seconds and string integers
2603 $mtime = (int)$mtime;
2604 if ( $mtime <= 0 ) {
2605 // no last-modified time provided
2606 return $minTTL;
2609 $age = (int)$this->getCurrentTime() - $mtime;
2611 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
2615 * @internal For use by unit tests only
2616 * @return int
2617 * @since 1.30
2619 final public function getWarmupKeyMisses() {
2620 // Number of misses in $this->warmupCache during the last call to certain methods
2621 return $this->warmupKeyMisses;
2625 * Set a sister key to a purge value in all datacenters
2627 * This method should not wait for the operation to complete on remote datacenters
2629 * Since older purge values can sometimes arrive after newer ones, use a relative expiry
2630 * so that even if the older value replaces the newer value, the TTL will greater than the
2631 * remaining TTL on the older value (assuming that all purges for a key use the same TTL).
2633 * @param string $sisterKey A value key or "check" key
2634 * @param string $purgeValue Result of makeTombstonePurgeValue()/makeCheckKeyPurgeValue()
2635 * @param int $ttl Seconds to keep the purge value around
2636 * @return bool Success
2638 protected function relayVolatilePurge( string $sisterKey, string $purgeValue, int $ttl ) {
2639 if ( $this->broadcastRoute !== null ) {
2640 $routeKey = $this->prependRoute( $sisterKey, $this->broadcastRoute );
2641 } else {
2642 $routeKey = $sisterKey;
2645 return $this->cache->set(
2646 $routeKey,
2647 $purgeValue,
2648 $ttl,
2649 $this->cache::WRITE_BACKGROUND
2654 * Remove a sister key from all datacenters
2656 * This method should not wait for the operation to complete on remote datacenters
2658 * @param string $sisterKey A value key or "check" key
2659 * @return bool Success
2661 protected function relayNonVolatilePurge( string $sisterKey ) {
2662 if ( $this->broadcastRoute !== null ) {
2663 $routeKey = $this->prependRoute( $sisterKey, $this->broadcastRoute );
2664 } else {
2665 $routeKey = $sisterKey;
2668 return $this->cache->delete( $routeKey, $this->cache::WRITE_BACKGROUND );
2672 * @param string $sisterKey
2673 * @param string $route Key routing prefix
2674 * @return string
2676 protected function prependRoute( string $sisterKey, string $route ) {
2677 if ( $sisterKey[0] === '/' ) {
2678 throw new RuntimeException( "Sister key '$sisterKey' already contains a route." );
2681 return $route . $sisterKey;
2685 * Schedule a deferred cache regeneration if possible
2687 * @param string $key Cache key made with makeKey()/makeGlobalKey()
2688 * @param int $ttl Seconds to live
2689 * @param callable $callback
2690 * @param array $opts
2691 * @param array $cbParams
2692 * @return bool Success
2693 * @note Callable type hints are not used to avoid class-autoloading
2695 private function scheduleAsyncRefresh( $key, $ttl, $callback, array $opts, array $cbParams ) {
2696 if ( !$this->asyncHandler ) {
2697 return false;
2699 // Update the cache value later, such during post-send of an HTTP request. This forces
2700 // cache regeneration by setting "minAsOf" to infinity, meaning that no existing value
2701 // is considered valid. Furthermore, note that preemptive regeneration is not applicable
2702 // to invalid values, so there is no risk of infinite preemptive regeneration loops.
2703 $func = $this->asyncHandler;
2704 $func( function () use ( $key, $ttl, $callback, $opts, $cbParams ) {
2705 $opts['minAsOf'] = INF;
2706 try {
2707 $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams );
2708 } catch ( Exception $e ) {
2709 // Log some context for easier debugging
2710 $this->logger->error( 'Async refresh failed for {key}', [
2711 'key' => $key,
2712 'ttl' => $ttl,
2713 'exception' => $e
2714 ] );
2715 throw $e;
2717 } );
2719 return true;
2723 * Check if a key value is non-false, new enough, and either fresh or "gracefully" stale
2725 * @param array $res Current value WANObjectCache::RES_* data map
2726 * @param int $graceTTL Consider using stale values if $curTTL is greater than this
2727 * @param float $minAsOf Minimum acceptable value "as of" UNIX timestamp
2728 * @return bool
2730 private function isAcceptablyFreshValue( $res, $graceTTL, $minAsOf ) {
2731 if ( !$this->isValid( $res[self::RES_VALUE], $res[self::RES_AS_OF], $minAsOf ) ) {
2732 // Value does not exists or is too old
2733 return false;
2736 $curTTL = $res[self::RES_CUR_TTL];
2737 if ( $curTTL > 0 ) {
2738 // Value is definitely still fresh
2739 return true;
2742 // Remaining seconds during which this stale value can be used
2743 $curGraceTTL = $graceTTL + $curTTL;
2745 return ( $curGraceTTL > 0 )
2746 // Chance of using the value decreases as $curTTL goes from 0 to -$graceTTL
2747 ? !$this->worthRefreshExpiring( $curGraceTTL, $graceTTL, $graceTTL )
2748 // Value is too stale to fall in the grace period
2749 : false;
2753 * Check if a key is due for randomized regeneration due to near-expiration/popularity
2755 * @param array $res Current value WANObjectCache::RES_* data map
2756 * @param float $lowTTL Consider a refresh when $curTTL is less than this; the "low" threshold
2757 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
2758 * @param int $hotTTR Age of key when it should be refreshed if popular (seconds)
2759 * @param float $now The current UNIX timestamp
2760 * @return bool
2762 protected function isLotteryRefreshDue( $res, $lowTTL, $ageNew, $hotTTR, $now ) {
2763 $curTTL = $res[self::RES_CUR_TTL];
2764 $logicalTTL = $res[self::RES_TTL];
2765 $asOf = $res[self::RES_AS_OF];
2767 return (
2768 $this->worthRefreshExpiring( $curTTL, $logicalTTL, $lowTTL ) ||
2769 $this->worthRefreshPopular( $asOf, $ageNew, $hotTTR, $now )
2774 * Check if a key is due for randomized regeneration due to its popularity
2776 * This is used so that popular keys can preemptively refresh themselves for higher
2777 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
2778 * in cache with their high nominal TTL. This means popular keys keep good consistency,
2779 * whether the data changes frequently or not, and long-tail keys get to stay in cache
2780 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
2782 * @param float $asOf UNIX timestamp of the value
2783 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
2784 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
2785 * @param float $now The current UNIX timestamp
2786 * @return bool
2788 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
2789 if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
2790 return false;
2793 $age = $now - $asOf;
2794 $timeOld = $age - $ageNew;
2795 if ( $timeOld <= 0 ) {
2796 return false;
2799 $popularHitsPerSec = 1;
2800 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
2801 // Note that the "expected # of refreshes" for the ramp-up time range is half
2802 // of what it would be if P(refresh) was at its full value during that time range.
2803 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
2804 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
2805 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1 (by definition)
2806 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
2807 $chance = 1 / ( $popularHitsPerSec * $refreshWindowSec );
2808 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
2809 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
2811 return ( mt_rand( 1, 1_000_000_000 ) <= 1_000_000_000 * $chance );
2815 * Check if a key is nearing expiration and thus due for randomized regeneration
2817 * If $curTTL is greater than the "low" threshold (e.g. not nearing expiration) then this
2818 * returns false. If $curTTL <= 0 (e.g. value already expired), then this returns false.
2819 * Otherwise, the chance of this returning true increases steadily from 0% to 100% as
2820 * $curTTL moves from the "low" threshold down to 0 seconds.
2822 * The logical TTL will be used as the "low" threshold if it is less than $lowTTL.
2824 * This method uses deadline-aware randomization in order to handle wide variations
2825 * of cache access traffic without the need for configuration or expensive state.
2827 * @param float $curTTL Approximate TTL left on the key
2828 * @param float $logicalTTL Full logical TTL assigned to the key; 0 for "infinite"
2829 * @param float $lowTTL Consider a refresh when $curTTL is less than this; the "low" threshold
2830 * @return bool
2832 protected function worthRefreshExpiring( $curTTL, $logicalTTL, $lowTTL ) {
2833 if ( $lowTTL <= 0 ) {
2834 return false;
2836 // T264787: avoid having keys start off with a high chance of being refreshed;
2837 // the point where refreshing becomes possible cannot precede the key lifetime.
2838 $effectiveLowTTL = min( $lowTTL, $logicalTTL ?: INF );
2840 // How long the value was in the "low TTL" phase
2841 $timeOld = $effectiveLowTTL - $curTTL;
2842 if ( $timeOld <= 0 || $timeOld >= $effectiveLowTTL ) {
2843 return false;
2846 // Ratio of the low TTL phase that has elapsed (r)
2847 $ttrRatio = $timeOld / $effectiveLowTTL;
2848 // Use p(r) as the monotonically increasing "chance of refresh" function,
2849 // having p(0)=0 and p(1)=1. The value expires at the nominal expiry.
2850 $chance = $ttrRatio ** 4;
2852 return ( mt_rand( 1, 1_000_000_000 ) <= 1_000_000_000 * $chance );
2856 * Check that a wrapper value exists and has an acceptable age
2858 * @param array|false $value Value wrapper or false
2859 * @param float $asOf Value generation "as of" timestamp
2860 * @param float $minAsOf Minimum acceptable value "as of" UNIX timestamp
2861 * @return bool
2863 protected function isValid( $value, $asOf, $minAsOf ) {
2864 return ( $value !== false && $asOf >= $minAsOf );
2868 * @param mixed $value
2869 * @param int $ttl Seconds to live or zero for "indefinite"
2870 * @param int|null $version Value version number or null if not versioned
2871 * @param float $now Unix Current timestamp just before calling set()
2872 * @return array
2874 private function wrap( $value, $ttl, $version, $now ) {
2875 // Returns keys in ascending integer order for PHP7 array packing:
2876 // https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html
2877 $wrapped = [
2878 self::FLD_FORMAT_VERSION => self::VERSION,
2879 self::FLD_VALUE => $value,
2880 self::FLD_TTL => $ttl,
2881 self::FLD_TIME => $now
2883 if ( $version !== null ) {
2884 $wrapped[self::FLD_VALUE_VERSION] = $version;
2887 return $wrapped;
2891 * @param array|string|false $wrapped The entry at a cache key (false if key is nonexistant)
2892 * @param float $now Unix Current timestamp (preferably pre-query)
2893 * @return array<int,mixed> Result map/n-tuple that includes the following:
2894 * - WANObjectCache::RES_VALUE: value or false if absent/tombstoned/malformed
2895 * - WANObjectCache::KEY_VERSION: value version number; null if there is no value
2896 * - WANObjectCache::KEY_AS_OF: value generation timestamp (UNIX); null if there is no value
2897 * - WANObjectCache::KEY_TTL: assigned logical TTL (seconds); null if there is no value
2898 * - WANObjectCache::KEY_TOMB_AS_OF: tombstone timestamp (UNIX); null if not tombstoned
2899 * - WANObjectCache::RES_CHECK_AS_OF: null placeholder for highest "check" key timestamp
2900 * - WANObjectCache::RES_TOUCH_AS_OF: null placeholder for highest "touched" timestamp
2901 * - WANObjectCache::KEY_CUR_TTL: remaining logical TTL (seconds) (negative if tombstoned)
2902 * @phan-return array{0:mixed,1:mixed,2:?float,3:?int,4:?float,5:?float,6:?float,7:?float}
2904 private function unwrap( $wrapped, $now ) {
2905 // https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html
2906 $res = [
2907 // Attributes that only depend on the fetched key value
2908 self::RES_VALUE => false,
2909 self::RES_VERSION => null,
2910 self::RES_AS_OF => null,
2911 self::RES_TTL => null,
2912 self::RES_TOMB_AS_OF => null,
2913 // Attributes that depend on caller-specific "check" keys or "touched callbacks"
2914 self::RES_CHECK_AS_OF => null,
2915 self::RES_TOUCH_AS_OF => null,
2916 self::RES_CUR_TTL => null
2919 if ( is_array( $wrapped ) ) {
2920 // Entry expected to be a cached value; validate it
2921 if (
2922 ( $wrapped[self::FLD_FORMAT_VERSION] ?? null ) === self::VERSION &&
2923 $wrapped[self::FLD_TIME] >= $this->epoch
2925 if ( $wrapped[self::FLD_TTL] > 0 ) {
2926 // Get the approximate time left on the key
2927 $age = $now - $wrapped[self::FLD_TIME];
2928 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
2929 } else {
2930 // Key had no TTL, so the time left is unbounded
2931 $curTTL = INF;
2933 $res[self::RES_VALUE] = $wrapped[self::FLD_VALUE];
2934 $res[self::RES_VERSION] = $wrapped[self::FLD_VALUE_VERSION] ?? null;
2935 $res[self::RES_AS_OF] = $wrapped[self::FLD_TIME];
2936 $res[self::RES_CUR_TTL] = $curTTL;
2937 $res[self::RES_TTL] = $wrapped[self::FLD_TTL];
2939 } else {
2940 // Entry expected to be a tombstone; parse it
2941 $purge = $this->parsePurgeValue( $wrapped );
2942 if ( $purge !== null ) {
2943 // Tombstoned keys should always have a negative "current TTL"
2944 $curTTL = min( $purge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
2945 $res[self::RES_CUR_TTL] = $curTTL;
2946 $res[self::RES_TOMB_AS_OF] = $purge[self::PURGE_TIME];
2950 return $res;
2954 * @param string $key Cache key in the format `<keyspace>:<keygroup>[:<other components>]...`
2955 * as formatted by WANObjectCache::makeKey() or ::makeKeyGlobal.
2956 * @return string The key group of this cache key
2958 private function determineKeyGroupForStats( $key ) {
2959 $parts = explode( ':', $key, 3 );
2960 // Fallback in case the key was not made by makeKey.
2961 // Replace dots because they are special in StatsD (T232907)
2962 return strtr( $parts[1] ?? $parts[0], '.', '_' );
2966 * Extract purge metadata from cached value if it is a valid purge value
2968 * Valid purge values come from makeTombstonePurgeValue()/makeCheckKeyPurgeValue()
2970 * @param mixed $value Cached value
2971 * @return array|null Tuple of (UNIX timestamp, hold-off seconds); null if value is invalid
2973 private function parsePurgeValue( $value ) {
2974 if ( !is_string( $value ) ) {
2975 return null;
2978 $segments = explode( ':', $value, 3 );
2979 $prefix = $segments[0];
2980 if ( $prefix !== self::PURGE_VAL_PREFIX ) {
2981 // Not a purge value
2982 return null;
2985 $timestamp = (float)$segments[1];
2986 // makeTombstonePurgeValue() doesn't store hold-off TTLs
2987 $holdoff = isset( $segments[2] ) ? (int)$segments[2] : self::HOLDOFF_TTL;
2989 if ( $timestamp < $this->epoch ) {
2990 // Purge value is too old
2991 return null;
2994 return [ self::PURGE_TIME => $timestamp, self::PURGE_HOLDOFF => $holdoff ];
2998 * @param float $timestamp UNIX timestamp
2999 * @return string Wrapped purge value; format is "PURGED:<timestamp>"
3001 private function makeTombstonePurgeValue( float $timestamp ) {
3002 return self::PURGE_VAL_PREFIX . ':' . (int)$timestamp;
3006 * @param float $timestamp UNIX timestamp
3007 * @param int $holdoff In seconds
3008 * @param array|null &$purge Unwrapped purge value array [returned]
3009 * @return string Wrapped purge value; format is "PURGED:<timestamp>:<holdoff>"
3011 private function makeCheckPurgeValue( float $timestamp, int $holdoff, ?array &$purge = null ) {
3012 $normalizedTime = (int)$timestamp;
3013 // Purge array that matches what parsePurgeValue() would have returned
3014 $purge = [ self::PURGE_TIME => (float)$normalizedTime, self::PURGE_HOLDOFF => $holdoff ];
3016 return self::PURGE_VAL_PREFIX . ":$normalizedTime:$holdoff";
3020 * @param string $group
3021 * @return MapCacheLRU
3023 private function getProcessCache( $group ) {
3024 if ( !isset( $this->processCaches[$group] ) ) {
3025 [ , $size ] = explode( ':', $group );
3026 $this->processCaches[$group] = new MapCacheLRU( (int)$size );
3027 if ( $this->wallClockOverride !== null ) {
3028 $this->processCaches[$group]->setMockTime( $this->wallClockOverride );
3032 return $this->processCaches[$group];
3036 * @param ArrayIterator $keys
3037 * @param array $opts
3038 * @return string[] Map of (ID => cache key)
3040 private function getNonProcessCachedMultiKeys( ArrayIterator $keys, array $opts ) {
3041 $pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
3043 $keysMissing = [];
3044 if ( $pcTTL > 0 && $this->callbackDepth == 0 ) {
3045 $pCache = $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY );
3046 foreach ( $keys as $key => $id ) {
3047 if ( !$pCache->has( $key, $pcTTL ) ) {
3048 $keysMissing[$id] = $key;
3053 return $keysMissing;
3057 * @param string[] $keys Cache keys made with makeKey()/makeGlobalKey()
3058 * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s));
3059 * "check" keys must also be made with makeKey()/makeGlobalKey()
3060 * @return array<string,mixed> Map of (sister key => value, or, false if not found)
3062 private function fetchWrappedValuesForWarmupCache( array $keys, array $checkKeys ) {
3063 if ( !$keys ) {
3064 return [];
3067 // Get all the value keys to fetch...
3068 $sisterKeys = $this->makeSisterKeys( $keys, self::TYPE_VALUE );
3069 // Get all the "check" keys to fetch...
3070 foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) {
3071 // Note: avoid array_merge() inside loop in case there are many keys
3072 if ( is_int( $i ) ) {
3073 // Single "check" key that applies to all value keys
3074 $sisterKeys[] = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP );
3075 } else {
3076 // List of "check" keys that apply to a specific value key
3077 foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) {
3078 $sisterKeys[] = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP );
3083 $wrappedBySisterKey = $this->cache->getMulti( $sisterKeys );
3084 $wrappedBySisterKey += array_fill_keys( $sisterKeys, false );
3086 return $wrappedBySisterKey;
3090 * @param string $key Cache key made with makeKey()/makeGlobalKey()
3091 * @param float $now Current UNIX timestamp
3092 * @return float|null Seconds since the last logged get() miss for this key, or, null
3094 private function timeSinceLoggedMiss( $key, $now ) {
3095 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.Found
3096 for ( end( $this->missLog ); $miss = current( $this->missLog ); prev( $this->missLog ) ) {
3097 if ( $miss[0] === $key ) {
3098 return ( $now - $miss[1] );
3102 return null;
3106 * @return float UNIX timestamp
3107 * @codeCoverageIgnore
3109 protected function getCurrentTime() {
3110 return $this->wallClockOverride ?: microtime( true );
3114 * @param float|null &$time Mock UNIX timestamp for testing
3115 * @codeCoverageIgnore
3117 public function setMockTime( &$time ) {
3118 $this->wallClockOverride =& $time;
3119 $this->cache->setMockTime( $time );
3120 foreach ( $this->processCaches as $pCache ) {
3121 $pCache->setMockTime( $time );
3126 /** @deprecated class alias since 1.43 */
3127 class_alias( WANObjectCache::class, 'WANObjectCache' );