1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Cache
20 */
21
22use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
23use Psr\Log\LoggerAwareInterface;
24use Psr\Log\LoggerInterface;
25use Psr\Log\NullLogger;
26use Wikimedia\LightweightObjectStore\ExpirationAwareness;
27use Wikimedia\LightweightObjectStore\StorageAwareness;
28
29/**
30 * Multi-datacenter aware caching interface
31 *
32 * ### Using WANObjectCache
33 *
34 * All operations go to the local datacenter cache, except for delete(),
35 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
36 *
37 * This class is intended for caching data from primary stores.
38 * If the get() method does not return a value, then the caller
39 * should query the new value and backfill the cache using set().
40 * The preferred way to do this logic is through getWithSetCallback().
41 * When querying the store on cache miss, the closest DB replica
42 * should be used. Try to avoid heavyweight DB master or quorum reads.
43 *
44 * To ensure consumers of the cache see new values in a timely manner,
45 * you either need to follow either the validation strategy, or the
46 * purge strategy.
47 *
48 * The validation strategy refers to the natural avoidance of stale data
49 * by one of the following means:
50 *
51 *   - A) The cached value is immutable.
52 *        If the consumer has access to an identifier that uniquely describes a value,
53 *        cached value need not change. Instead, the key can change. This also allows
54 *        all servers to access their perceived current version. This is important
55 *        in context of multiple deployed versions of your application and/or cross-dc
56 *        database replication, to ensure deterministic values without oscillation.
57 *   - B) Validity is checked against the source after get().
58 *        This is the inverse of A. The unique identifier is embedded inside the value
59 *        and validated after on retreival. If outdated, the value is recomputed.
60 *   - C) The value is cached with a modest TTL (without validation).
61 *        If value recomputation is reasonably performant, and the value is allowed to
62 *        be stale, one should consider using TTL only – using the value's age as
63 *        method of validation.
64 *
65 * The purge strategy refers to the approach whereby your application knows that
66 * source data has changed and can react by purging the relevant cache keys.
67 * As purges are expensive, this strategy should be avoided if possible.
68 * The simplest purge method is delete().
69 *
70 * No matter which strategy you choose, callers must not rely on updates or purges
71 * being immediately visible to other servers. It should be treated similarly as
72 * one would a database replica.
73 *
74 * The need for immediate updates should be avoided. If needed, solutions must be
75 * sought outside WANObjectCache.
76 *
77 * @anchor wanobjectcache-deployment
78 * ### Deploying %WANObjectCache
79 *
80 * There are two supported ways to set up broadcasted operations:
81 *
82 *   - A) Set up mcrouter as the underlying cache backend, using a memcached BagOStuff class
83 *        for the 'cache' parameter. The 'broadcastRoutingPrefix' parameter must be provided.
84 *        Configure mcrouter as follows:
85 *          - 1) Use Route Prefixing based on region (datacenter) and cache cluster.
86 *               See https://github.com/facebook/mcrouter/wiki/Routing-Prefix and
87 *               https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup.
88 *          - 2) To increase the consistency of delete() and touchCheckKey() during cache
89 *               server membership changes, you can use the OperationSelectorRoute to
90 *               configure 'set' and 'delete' operations to go to all servers in the cache
91 *               cluster, instead of just one server determined by hashing.
92 *               See https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles.
93 *   - B) Set up dynomite as a cache middleware between the web servers and either memcached
94 *        or redis and use it as the underlying cache backend, using a memcached BagOStuff
95 *        class for the 'cache' parameter. This will broadcast all key setting operations,
96 *        not just purges, which can be useful for cache warming. Writes are eventually
97 *        consistent via the Dynamo replication model. See https://github.com/Netflix/dynomite.
98 *
99 * Broadcasted operations like delete() and touchCheckKey() are intended to run
100 * immediately in the local datacenter and asynchronously in remote datacenters.
101 *
102 * This means that callers in all datacenters may see older values for however many
103 * milliseconds that the purge took to reach that datacenter. As with any cache, this
104 * should not be relied on for cases where reads are used to determine writes to source
105 * (e.g. non-cache) data stores, except when reading immutable data.
106 *
107 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix to avoid
108 * collisions with keys that are not wrapped as metadata arrays. For any given key that
109 * a caller uses, there are several "sister" keys that might be involved under the hood.
110 * Each "sister" key differs only by a single-character:
111 *   - v: used for regular value keys
112 *   - i: used for temporarily storing values of tombstoned keys
113 *   - t: used for storing timestamp "check" keys
114 *   - m: used for temporary mutex keys to avoid cache stampedes
115 *
116 * @ingroup Cache
117 * @since 1.26
118 */
119class WANObjectCache implements
120	ExpirationAwareness,
121	StorageAwareness,
122	IStoreKeyEncoder,
123	LoggerAwareInterface
124{
125	/** @var BagOStuff The local datacenter cache */
126	protected $cache;
127	/** @var MapCacheLRU[] Map of group PHP instance caches */
128	protected $processCaches = [];
129	/** @var LoggerInterface */
130	protected $logger;
131	/** @var StatsdDataFactoryInterface */
132	protected $stats;
133	/** @var callable|null Function that takes a WAN cache callback and runs it later */
134	protected $asyncHandler;
135
136	/**
137	 * Routing prefix for values that should be broadcasted to all data centers.
138	 *
139	 * If null, then a proxy other than mcrouter handles broadcasting or there is only one datacenter.
140	 *
141	 * @var string|null
142	 */
143	protected $broadcastRoute;
144	/** @var string|null Routing prefix for value keys that support use of an on-host tier */
145	protected $onHostRoute;
146	/** @var bool Whether to use "interim" caching while keys are tombstoned */
147	protected $useInterimHoldOffCaching = true;
148	/** @var float Unix timestamp of the oldest possible valid values */
149	protected $epoch;
150	/** @var string Stable secret used for hasing long strings into key components */
151	protected $secret;
152	/** @var int Scheme to use for key coalescing (Hash Tags or Hash Stops) */
153	protected $coalesceScheme;
154
155	/** @var int Reads/second assumed during a hypothetical cache write stampede for a key */
156	private $keyHighQps;
157	/** @var float Max tolerable bytes/second to spend on a cache write stampede for a key */
158	private $keyHighUplinkBps;
159
160	/** @var int Callback stack depth for getWithSetCallback() */
161	private $callbackDepth = 0;
162	/** @var mixed[] Temporary warm-up cache */
163	private $warmupCache = [];
164	/** @var int Key fetched */
165	private $warmupKeyMisses = 0;
166
167	/** @var float|null */
168	private $wallClockOverride;
169
170	/** Max expected seconds to pass between delete() and DB commit finishing */
171	private const MAX_COMMIT_DELAY = 3;
172	/** Max expected seconds of combined lag from replication and view snapshots */
173	private const MAX_READ_LAG = 7;
174	/** Seconds to tombstone keys on delete() and treat as volatile after invalidation */
175	public const HOLDOFF_TTL = self::MAX_COMMIT_DELAY + self::MAX_READ_LAG + 1;
176
177	/** Consider regeneration if the key will expire within this many seconds */
178	private const LOW_TTL = 30;
179	/** Max TTL, in seconds, to store keys when a data sourced is lagged */
180	public const TTL_LAGGED = 30;
181
182	/** Expected time-till-refresh, in seconds, if the key is accessed once per second */
183	private const HOT_TTR = 900;
184	/** Minimum key age, in seconds, for expected time-till-refresh to be considered */
185	private const AGE_NEW = 60;
186
187	/** Idiom for getWithSetCallback() meaning "no cache stampede mutex" */
188	private const TSE_NONE = -1;
189
190	/** Idiom for set()/getWithSetCallback() meaning "no post-expiration persistence" */
191	public const STALE_TTL_NONE = 0;
192	/** Idiom for set()/getWithSetCallback() meaning "no post-expiration grace period" */
193	public const GRACE_TTL_NONE = 0;
194	/** Idiom for delete()/touchCheckKey() meaning "no hold-off period" */
195	public const HOLDOFF_TTL_NONE = 0;
196	/** Alias for HOLDOFF_TTL_NONE (b/c) (deprecated since 1.34) */
197	public const HOLDOFF_NONE = self::HOLDOFF_TTL_NONE;
198
199	/** @var float Idiom for getWithSetCallback() meaning "no minimum required as-of timestamp" */
200	public const MIN_TIMESTAMP_NONE = 0.0;
201
202	/** Default process cache name and max key count */
203	private const PC_PRIMARY = 'primary:1000';
204
205	/** Idiom for get()/getMulti() to return extra information by reference */
206	public const PASS_BY_REF = [];
207
208	/** Use twemproxy-style Hash Tag key scheme (e.g. "{...}") */
209	private const SCHEME_HASH_TAG = 1;
210	/** Use mcrouter-style Hash Stop key scheme (e.g. "...|#|") */
211	private const SCHEME_HASH_STOP = 2;
212
213	/** Seconds to keep dependency purge keys around */
214	private const CHECK_KEY_TTL = self::TTL_YEAR;
215	/** Seconds to keep interim value keys for tombstoned keys around */
216	private const INTERIM_KEY_TTL = 1;
217
218	/** Seconds to keep lock keys around */
219	private const LOCK_TTL = 10;
220	/** Seconds to no-op key set() calls to avoid large blob I/O stampedes */
221	private const COOLOFF_TTL = 1;
222	/** Seconds to ramp up the chance of regeneration due to expected time-till-refresh */
223	private const RAMPUP_TTL = 30;
224
225	/** @var float Tiny negative float to use when CTL comes up >= 0 due to clock skew */
226	private const TINY_NEGATIVE = -0.000001;
227	/** @var float Tiny positive float to use when using "minTime" to assert an inequality */
228	private const TINY_POSTIVE = 0.000001;
229
230	/** Min millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL) */
231	private const RECENT_SET_LOW_MS = 50;
232	/** Max millisecond set() backoff during hold-off (far less than INTERIM_KEY_TTL) */
233	private const RECENT_SET_HIGH_MS = 100;
234
235	/** Consider value generation slow if it takes more than this many seconds */
236	private const GENERATION_SLOW_SEC = 3;
237
238	/** Key to the tombstone entry timestamp */
239	private const PURGE_TIME = 0;
240	/** Key to the tombstone entry hold-off TTL */
241	private const PURGE_HOLDOFF = 1;
242
243	/** Cache format version number */
244	private const VERSION = 1;
245
246	/** The key value component of a fetchMulti() result */
247	private const RES_VALUE = 0;
248	/** The key metadata component of a fetchMulti() result */
249	private const RES_METADATA = 1;
250
251	/** Version number attribute for a key; keep value for b/c (< 1.36) */
252	public const KEY_VERSION = 'version';
253	/** Generation timestamp attribute for a key; keep value for b/c (< 1.36) */
254	public const KEY_AS_OF = 'asOf';
255	/** Logical TTL attribute for a key */
256	public const KEY_TTL = 'ttl';
257	/** Remaining TTL attribute for a key; keep value for b/c (< 1.36) */
258	public const KEY_CUR_TTL = 'curTTL';
259	/** Tomstone timestamp attribute for a key; keep value for b/c (< 1.36) */
260	public const KEY_TOMB_AS_OF = 'tombAsOf';
261	/** Highest "check" key timestamp for a key; keep value for b/c (< 1.36) */
262	public const KEY_CHECK_AS_OF = 'lastCKPurge';
263
264	/** Key to WAN cache version number */
265	private const FLD_FORMAT_VERSION = 0;
266	/** Key to the cached value */
267	private const FLD_VALUE = 1;
268	/** Key to the original TTL */
269	private const FLD_TTL = 2;
270	/** Key to the cache timestamp */
271	private const FLD_TIME = 3;
272	/** Key to the flags bit field (reserved number) */
273	private const /** @noinspection PhpUnusedPrivateFieldInspection */ FLD_FLAGS = 4;
274	/** Key to collection cache version number */
275	private const FLD_VALUE_VERSION = 5;
276	/** Key to how long it took to generate the value */
277	private const FLD_GENERATION_TIME = 6;
278
279	/** Single character value mutex key component */
280	private const TYPE_VALUE = 'v';
281	/** Single character timestamp key component */
282	private const TYPE_TIMESTAMP = 't';
283	/** Single character flux key component */
284	private const TYPE_FLUX = 'f';
285	/** Single character mutex key component */
286	private const TYPE_MUTEX = 'm';
287	/** Single character interium key component */
288	private const TYPE_INTERIM = 'i';
289	/** Single character cool-off key component */
290	private const TYPE_COOLOFF = 'c';
291
292	/** Prefix for tombstone key values */
293	private const PURGE_VAL_PREFIX = 'PURGED:';
294
295	/**
296	 * @param array $params
297	 *   - cache    : BagOStuff object for a persistent cache
298	 *   - logger   : LoggerInterface object
299	 *   - stats    : StatsdDataFactoryInterface object
300	 *   - asyncHandler : A function that takes a callback and runs it later. If supplied,
301	 *       whenever a preemptive refresh would be triggered in getWithSetCallback(), the
302	 *       current cache value is still used instead. However, the async-handler function
303	 *       receives a WAN cache callback that, when run, will execute the value generation
304	 *       callback supplied by the getWithSetCallback() caller. The result will be saved
305	 *       as normal. The handler is expected to call the WAN cache callback at an opportune
306	 *       time (e.g. HTTP post-send), though generally within a few 100ms. [optional]
307	 *   - broadcastRoutingPrefix: a routing prefix used to broadcast "set" and "delete" operations to all
308	 *       datacenters; See also https://github.com/facebook/mcrouter/wiki/Config-Files for background
309	 *       on this.
310	 *       This prefix takes the form `/<datacenter>/<name of wan route>/` where `datacenter` should
311	 *       generally be a wildcard, to select all matching routes (e.g. the WAN cluster in all DCs)
312	 *       See also <https://github.com/facebook/mcrouter/wiki/Multi-cluster-broadcast-setup>.
313	 *       This is required when using mcrouter as the backing store proxy. [optional]
314	 *   - onHostRoutingPrefix: a routing prefix that considers a server-local cache ("on-host tier")
315	 *       for "value" keys before reading from the main cache cluster in the current data center.
316	 *       The "helper" keys will still be read from the main cache cluster. An on-host tier can help
317	 *       reduce network saturation due to large value transfers yet without needing to explicitly
318	 *       know, opt-in, or measure which values are large.
319	 *       The on-host tier may blindy store and serve values from the main cluster for up to 10
320	 *       seconds (must be less than WANObjectCache::HOLDOFF_TTL, as otherwise WANObjectCache will
321	 *       be unable to apply purges from the main cluster, which don't live longer than that).
322	 *       This prefix takes the form `/<datacenter>/<name of onhost route>/` where `datacenter`
323	 *       may be a wildcard. This can be used with mcrouter. [optional]
324	 *   - epoch: lowest UNIX timestamp a value/tombstone must have to be valid. [optional]
325	 *   - secret: stable secret used for hashing long strings into key components. [optional]
326	 *   - coalesceScheme: which key scheme to use in order to encourage the backend to place any
327	 *       "helper" keys for a "value" key within the same cache server. This reduces network
328	 *       overhead and reduces the chance the a single downed cache server causes disruption.
329	 *       Use "hash_stop" with mcrouter and "hash_tag" with dynomite. [default: "hash_stop"]
330	 *   - keyHighQps: reads/second assumed during a hypothetical cache write stampede for
331	 *       a single key. This is used to decide when the overhead of checking short-lived
332	 *       write throttling keys is worth it.
333	 *       [default: 100]
334	 *   - keyHighUplinkBps: maximum tolerable bytes/second to spend on a cache write stampede
335	 *       for a single key. This is used to decide when the overhead of checking short-lived
336	 *       write throttling keys is worth it. [default: (1/100 of a 1Gbps link)]
337	 */
338	public function __construct( array $params ) {
339		$this->cache = $params['cache'];
340		$this->broadcastRoute = $params['broadcastRoutingPrefix'] ?? null;
341		$this->onHostRoute = $params['onHostRoutingPrefix'] ?? null;
342		$this->epoch = $params['epoch'] ?? 0;
343		$this->secret = $params['secret'] ?? (string)$this->epoch;
344		if ( ( $params['coalesceScheme'] ?? '' ) === 'hash_tag' ) {
345			// https://redis.io/topics/cluster-spec
346			// https://github.com/twitter/twemproxy/blob/v0.4.1/notes/recommendation.md#hash-tags
347			// https://github.com/Netflix/dynomite/blob/v0.7.0/notes/recommendation.md#hash-tags
348			$this->coalesceScheme = self::SCHEME_HASH_TAG;
349		} else {
350			// https://github.com/facebook/mcrouter/wiki/Key-syntax
351			$this->coalesceScheme = self::SCHEME_HASH_STOP;
352		}
353
354		$this->keyHighQps = $params['keyHighQps'] ?? 100;
355		$this->keyHighUplinkBps = $params['keyHighUplinkBps'] ?? ( 1e9 / 8 / 100 );
356
357		$this->setLogger( $params['logger'] ?? new NullLogger() );
358		$this->stats = $params['stats'] ?? new NullStatsdDataFactory();
359		$this->asyncHandler = $params['asyncHandler'] ?? null;
360
361		$this->cache->registerWrapperInfoForStats(
362			'WANCache',
363			'wanobjectcache',
364			[ __CLASS__, 'getCollectionFromSisterKey' ]
365		);
366	}
367
368	/**
369	 * @param LoggerInterface $logger
370	 */
371	public function setLogger( LoggerInterface $logger ) {
372		$this->logger = $logger;
373	}
374
375	/**
376	 * Get an instance that wraps EmptyBagOStuff
377	 *
378	 * @return WANObjectCache
379	 */
380	public static function newEmpty() {
381		return new static( [ 'cache' => new EmptyBagOStuff() ] );
382	}
383
384	/**
385	 * Fetch the value of a key from cache
386	 *
387	 * If supplied, $curTTL is set to the remaining TTL (current time left):
388	 *   - a) INF; if $key exists, has no TTL, and is not invalidated by $checkKeys
389	 *   - b) float (>=0); if $key exists, has a TTL, and is not invalidated by $checkKeys
390	 *   - c) float (<0); if $key is tombstoned, stale, or existing but invalidated by $checkKeys
391	 *   - d) null; if $key does not exist and is not tombstoned
392	 *
393	 * If a key is tombstoned, $curTTL will reflect the time since delete().
394	 *
395	 * The timestamp of $key will be checked against the last-purge timestamp
396	 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
397	 * initialized to the current timestamp. If any of $checkKeys have a timestamp
398	 * greater than that of $key, then $curTTL will reflect how long ago $key
399	 * became invalid. Callers can use $curTTL to know when the value is stale.
400	 * The $checkKeys parameter allow mass invalidations by updating a single key:
401	 *   - a) Each "check" key represents "last purged" of some source data
402	 *   - b) Callers pass in relevant "check" keys as $checkKeys in get()
403	 *   - c) When the source data that "check" keys represent changes,
404	 *        the touchCheckKey() method is called on them
405	 *
406	 * Source data entities might exists in a DB that uses snapshot isolation
407	 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
408	 * isolation can largely be maintained by doing the following:
409	 *   - a) Calling delete() on entity change *and* creation, before DB commit
410	 *   - b) Keeping transaction duration shorter than the delete() hold-off TTL
411	 *   - c) Disabling interim key caching via useInterimHoldOffCaching() before get() calls
412	 *
413	 * However, pre-snapshot values might still be seen if an update was made
414	 * in a remote datacenter but the purge from delete() didn't relay yet.
415	 *
416	 * Consider using getWithSetCallback(), which has cache slam avoidance and key
417	 * versioning features, instead of bare get()/set() calls.
418	 *
419	 * Do not use this method on versioned keys accessed via getWithSetCallback().
420	 *
421	 * When using the $info parameter, it should be passed in as WANObjectCache::PASS_BY_REF.
422	 * In that case, it becomes a key metadata map. Otherwise, for backwards compatibility,
423	 * $info becomes the value generation timestamp (null if the key is nonexistant/tombstoned).
424	 * Key metadata map fields include:
425	 *   - WANObjectCache::KEY_VERSION: value version number; null if key is nonexistant
426	 *   - WANObjectCache::KEY_AS_OF: value generation timestamp (UNIX); null if key is nonexistant
427	 *   - WANObjectCache::KEY_TTL: assigned TTL (seconds); null if key is nonexistant/tombstoned
428	 *   - WANObjectCache::KEY_CUR_TTL: remaining TTL (seconds); null if key is nonexistant
429	 *   - WANObjectCache::KEY_TOMB_AS_OF: tombstone timestamp (UNIX); null if key is not tombstoned
430	 *   - WANObjectCache::KEY_CHECK_AS_OF: highest "check" key timestamp (UNIX); null if none
431	 *
432	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
433	 * @param float|null &$curTTL Seconds of TTL left [returned]
434	 * @param string[] $checkKeys Map of (integer or cache key => "check" key(s));
435	 *  "check" keys must also be made with makeKey()/makeGlobalKey()
436	 * @param array &$info Metadata map [returned]
437	 * @return mixed Value of cache key; false on failure
438	 */
439	final public function get( $key, &$curTTL = null, array $checkKeys = [], &$info = [] ) {
440		// Note that an undeclared variable passed as $info starts as null (not the default).
441		// Also, if no $info parameter is provided, then it doesn't matter how it changes here.
442		$legacyInfo = ( $info !== self::PASS_BY_REF );
443
444		$res = $this->fetchKeys( [ $key ], $checkKeys )[$key];
445		$value = $res[self::RES_VALUE];
446		$metadata = $res[self::RES_METADATA];
447
448		$curTTL = $metadata[self::KEY_CUR_TTL];
449		$info = $legacyInfo ? $metadata[self::KEY_AS_OF] : $metadata;
450
451		return $value;
452	}
453
454	/**
455	 * Fetch the value of several keys from cache
456	 *
457	 * $curTTLs becomes a map of only present/tombstoned $keys to their current time-to-live.
458	 *
459	 * $checkKeys holds the "check" keys used to validate values of applicable keys. The
460	 * integer indexes hold "check" keys that apply to all of $keys while the string indexes
461	 * hold "check" keys that only apply to the cache key with that name. The logic of "check"
462	 * keys otherwise works the same as in WANObjectCache::get().
463	 *
464	 * When using the $info parameter, it should be passed in as WANObjectCache::PASS_BY_REF.
465	 * In that case, it becomes a mapping of all the $keys to their metadata maps, each in the
466	 * style of WANObjectCache::get(). Otherwise, for backwards compatibility, $info becomes a
467	 * map of only present/tombstoned $keys to their value generation timestamps.
468	 *
469	 * @see WANObjectCache::get()
470	 *
471	 * @param string[] $keys List/map with makeKey()/makeGlobalKey() cache keys as values
472	 * @param array<string,float> &$curTTLs Map of (key => seconds of TTL left) [returned]
473	 * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s));
474	 *  "check" keys must also be made with makeKey()/makeGlobalKey()
475	 * @param array<string,array> &$info Map of (key => metadata map) [returned]
476	 * @return array<string,mixed> Map of (key => value) for existing values in order of $keys
477	 */
478	final public function getMulti(
479		array $keys,
480		&$curTTLs = [],
481		array $checkKeys = [],
482		&$info = []
483	) {
484		// Note that an undeclared variable passed as $info starts as null (not the default).
485		// Also, if no $info parameter is provided, then it doesn't matter how it changes here.
486		$legacyInfo = ( $info !== self::PASS_BY_REF );
487
488		$curTTLs = [];
489		$info = [];
490		$valuesByKey = [];
491
492		$resByKey = $this->fetchKeys( $keys, $checkKeys );
493		foreach ( $resByKey as $key => $res ) {
494			$value = $res[self::RES_VALUE];
495			$metadata = $res[self::RES_METADATA];
496
497			if ( $value !== false ) {
498				$valuesByKey[$key] = $value;
499			}
500
501			if ( $metadata[self::KEY_CUR_TTL] !== null ) {
502				$curTTLs[$key] = $metadata[self::KEY_CUR_TTL];
503			}
504
505			$info[$key] = $legacyInfo ? $metadata[self::KEY_AS_OF] : $metadata;
506		}
507
508		return $valuesByKey;
509	}
510
511	/**
512	 * Fetch the value and key metadata of several keys from cache
513	 *
514	 * $checkKeys holds the "check" keys used to validate values of applicable keys.
515	 * The integer indexes hold "check" keys that apply to all of $keys while the string
516	 * indexes hold "check" keys that only apply to the cache key with that name.
517	 *
518	 * This returns a map of (key => result map), with entries for each key in $key.
519	 * Result maps include the following fields:
520	 *  - WANObjectCache::RESULT_VALUE: the value; false if tombstoned/nonexistent
521	 *  - WANObjectCache::RESULT_ATTRIBUTES: the WANObjectCache::KEY_* metadata map
522	 *
523	 * @param string[] $keys List/map with makeKey()/makeGlobalKey() cache keys as values
524	 * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s));
525	 *  "check" keys must also be made with makeKey()/makeGlobalKey()
526	 * @return array<string,array{0:mixed,1:array}> Map of (key => result map) in order of $keys
527	 */
528	protected function fetchKeys( array $keys, array $checkKeys ) {
529		$resByKey = [];
530
531		// List of all sister keys that need to be fetched from cache
532		$allSisterKeys = [];
533		// Order-corresponding value sister key list for the base key list ($keys)
534		$valueSisterKeys = [];
535		// Order-corresponding "flux" sister key list for the base key list ($keys) or []
536		$fluxSisterKeys = [];
537		// List of "check" sister keys to compare all value sister keys against
538		$checkSisterKeysForAll = [];
539		// Map of (base key => additional "check" sister key(s) to compare against)
540		$checkSisterKeysByKey = [];
541
542		foreach ( $keys as $key ) {
543			$sisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE, $this->onHostRoute );
544			$allSisterKeys[] = $sisterKey;
545			$valueSisterKeys[] = $sisterKey;
546			if ( $this->onHostRoute !== null ) {
547				$sisterKey = $this->makeSisterKey( $key, self::TYPE_FLUX );
548				$allSisterKeys[] = $sisterKey;
549				$fluxSisterKeys[] = $sisterKey;
550			}
551		}
552
553		foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) {
554			// Note: avoid array_merge() inside loop in case there are many keys
555			if ( is_int( $i ) ) {
556				// Single "check" key that applies to all base keys
557				$sisterKey = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP );
558				$allSisterKeys[] = $sisterKey;
559				$checkSisterKeysForAll[] = $sisterKey;
560			} else {
561				// List of "check" keys that apply to a specific base key
562				foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) {
563					$sisterKey = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP );
564					$allSisterKeys[] = $sisterKey;
565					$checkSisterKeysByKey[$i][] = $sisterKey;
566				}
567			}
568		}
569
570		if ( $this->warmupCache ) {
571			// Get the wrapped values of the sister keys from the warmup cache
572			$wrappedBySisterKey = $this->warmupCache;
573			$sisterKeysMissing = array_diff( $allSisterKeys, array_keys( $wrappedBySisterKey ) );
574			if ( $sisterKeysMissing ) { // sanity
575				$this->warmupKeyMisses += count( $sisterKeysMissing );
576				$wrappedBySisterKey += $this->cache->getMulti( $sisterKeysMissing );
577			}
578		} else {
579			// Fetch the wrapped values of the sister keys from the backend
580			$wrappedBySisterKey = $this->cache->getMulti( $allSisterKeys );
581		}
582
583		// Pessimistically treat the "current time" as the time when any network I/O finished
584		$now = $this->getCurrentTime();
585
586		// List of "check" sister key purge timestamps to compare all value sister keys against
587		$ckPurgesForAll = $this->processCheckKeys(
588			$checkSisterKeysForAll,
589			$wrappedBySisterKey,
590			$now
591		);
592		// Map of (base key => extra "check" sister key purge timestamp(s) to compare against)
593		$ckPurgesByKey = [];
594		foreach ( $checkSisterKeysByKey as $keyWithCheckKeys => $checkKeysForKey ) {
595			$ckPurgesByKey[$keyWithCheckKeys] = $this->processCheckKeys(
596				$checkKeysForKey,
597				$wrappedBySisterKey,
598				$now
599			);
600		}
601
602		// Map of (base key => "flux" key purge timestamp to compare against)
603		$fkPurgesByKey = $this->processFluxKeys( $keys, $fluxSisterKeys, $wrappedBySisterKey );
604
605		// Unwrap and validate any value found for each base key (under the value sister key)
606		reset( $keys );
607		foreach ( $valueSisterKeys as $valueSisterKey ) {
608			// Get the corresponding base key for this value sister key
609			$key = current( $keys );
610			next( $keys );
611
612			if ( isset( $fkPurgesByKey[$key] ) ) {
613				// An on-host tier is in use and a "flux" sister key exists for this
614				// Treat the value sister key as if it was a tombstone with this value.
615				$wrapped = $fkPurgesByKey[$key];
616			} elseif ( array_key_exists( $valueSisterKey, $wrappedBySisterKey ) ) {
617				// Key exists as either a live value or tombstone value
618				$wrapped = $wrappedBySisterKey[$valueSisterKey];
619			} else {
620				// Key does not exist
621				$wrapped = false;
622			}
623
624			list( $value, $metadata ) = $this->unwrap( $wrapped, $now );
625			// Include the timestamp of the newest "check" key purge/initialization
626			$metadata[self::KEY_CHECK_AS_OF] = null;
627
628			foreach ( array_merge( $ckPurgesForAll, $ckPurgesByKey[$key] ?? [] ) as $ckPurge ) {
629				$metadata[self::KEY_CHECK_AS_OF] = max(
630					$ckPurge[self::PURGE_TIME],
631					$metadata[self::KEY_CHECK_AS_OF]
632				);
633				// Timestamp marking the end of the hold-off period for this purge
634				$holdoffDeadline = $ckPurge[self::PURGE_TIME] + $ckPurge[self::PURGE_HOLDOFF];
635				// Check if the value was generated during the hold-off period
636				if ( $value !== false && $holdoffDeadline >= $metadata[self::KEY_AS_OF] ) {
637					// How long ago this value was invalidated by *this* "check" key
638					$ago = min( $ckPurge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
639					// How long ago this value was invalidated by *any* known "check" key
640					$metadata[self::KEY_CUR_TTL] = min( $metadata[self::KEY_CUR_TTL], $ago );
641				}
642			}
643
644			$resByKey[$key] = [ self::RES_VALUE => $value, self::RES_METADATA => $metadata ];
645		}
646
647		return $resByKey;
648	}
649
650	/**
651	 * @param string[] $keys Base key list
652	 * @param string[] $fluxSisterKeys Order-corresponding "flux" key list for base keys or []
653	 * @param mixed[] $wrappedBySisterKey Preloaded map of (sister key => wrapped value)
654	 * @return array[] List of purge value arrays
655	 */
656	private function processFluxKeys(
657		array $keys,
658		array $fluxSisterKeys,
659		array $wrappedBySisterKey
660	) {
661		$purges = [];
662
663		reset( $keys );
664		foreach ( $fluxSisterKeys as $fluxKey ) {
665			// Get the corresponding base key for this "flux" key
666			$key = current( $keys );
667			next( $keys );
668
669			$purge = isset( $wrappedBySisterKey[$fluxKey] )
670				? $this->parsePurgeValue( $wrappedBySisterKey[$fluxKey] )
671				: false;
672
673			if ( $purge !== false ) {
674				$purges[$key] = $purge;
675			}
676		}
677
678		return $purges;
679	}
680
681	/**
682	 * @param string[] $checkSisterKeys List of "check" sister keys
683	 * @param mixed[] $wrappedBySisterKey Preloaded map of (sister key => wrapped value)
684	 * @param float $now UNIX timestamp
685	 * @return array[] List of purge value arrays
686	 */
687	private function processCheckKeys(
688		array $checkSisterKeys,
689		array $wrappedBySisterKey,
690		float $now
691	) {
692		$purges = [];
693
694		foreach ( $checkSisterKeys as $timeKey ) {
695			$purge = isset( $wrappedBySisterKey[$timeKey] )
696				? $this->parsePurgeValue( $wrappedBySisterKey[$timeKey] )
697				: false;
698
699			if ( $purge === false ) {
700				// Key is not set or malformed; regenerate
701				$newVal = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL );
702				$this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
703				$purge = $this->parsePurgeValue( $newVal );
704			}
705
706			$purges[] = $purge;
707		}
708
709		return $purges;
710	}
711
712	/**
713	 * Set the value of a key in cache
714	 *
715	 * Simply calling this method when source data changes is not valid because
716	 * the changes do not replicate to the other WAN sites. In that case, delete()
717	 * should be used instead. This method is intended for use on cache misses.
718	 *
719	 * If the data was read from a snapshot-isolated transactions (e.g. the default
720	 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
721	 *   - a) T1 starts
722	 *   - b) T2 updates a row, calls delete(), and commits
723	 *   - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
724	 *   - d) T1 reads the row and calls set() due to a cache miss
725	 *   - e) Stale value is stuck in cache
726	 *
727	 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
728	 *
729	 * Be aware that this does not update the process cache for getWithSetCallback()
730	 * callers. Keys accessed via that method are not generally meant to also be set
731	 * using this primitive method.
732	 *
733	 * Consider using getWithSetCallback(), which has cache slam avoidance and key
734	 * versioning features, instead of bare get()/set() calls.
735	 *
736	 * Do not use this method on versioned keys accessed via getWithSetCallback().
737	 *
738	 * Example usage:
739	 * @code
740	 *     $dbr = wfGetDB( DB_REPLICA );
741	 *     $setOpts = Database::getCacheSetOptions( $dbr );
742	 *     // Fetch the row from the DB
743	 *     $row = $dbr->selectRow( ... );
744	 *     $key = $cache->makeKey( 'building', $buildingId );
745	 *     $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
746	 * @endcode
747	 *
748	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
749	 * @param mixed $value
750	 * @param int $ttl Seconds to live. Special values are:
751	 *   - WANObjectCache::TTL_INDEFINITE: Cache forever (default)
752	 *   - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
753	 * @param array $opts Options map:
754	 *   - lag: Seconds of replica DB lag. Typically, this is either the replica DB lag
755	 *      before the data was read or, if applicable, the replica DB lag before
756	 *      the snapshot-isolated transaction the data was read from started.
757	 *      Use false to indicate that replication is not running.
758	 *      Default: 0 seconds
759	 *   - since: UNIX timestamp of the data in $value. Typically, this is either
760	 *      the current time the data was read or (if applicable) the time when
761	 *      the snapshot-isolated transaction the data was read from started.
762	 *      Default: 0 seconds
763	 *   - pending: Whether this data is possibly from an uncommitted write transaction.
764	 *      Generally, other threads should not see values from the future and
765	 *      they certainly should not see ones that ended up getting rolled back.
766	 *      Default: false
767	 *   - lockTSE: If excessive replication/snapshot lag is detected, then store the value
768	 *      with this TTL and flag it as stale. This is only useful if the reads for this key
769	 *      use getWithSetCallback() with "lockTSE" set. Note that if "staleTTL" is set
770	 *      then it will still add on to this TTL in the excessive lag scenario.
771	 *      Default: WANObjectCache::TSE_NONE
772	 *   - staleTTL: Seconds to keep the key around if it is stale. The get()/getMulti()
773	 *      methods return such stale values with a $curTTL of 0, and getWithSetCallback()
774	 *      will call the regeneration callback in such cases, passing in the old value
775	 *      and its as-of time to the callback. This is useful if adaptiveTTL() is used
776	 *      on the old value's as-of time when it is verified as still being correct.
777	 *      Default: WANObjectCache::STALE_TTL_NONE
778	 *   - creating: Optimize for the case where the key does not already exist.
779	 *      Default: false
780	 *   - version: Integer version number signifiying the format of the value.
781	 *      Default: null
782	 *   - walltime: How long the value took to generate in seconds. Default: null
783	 * @phpcs:ignore Generic.Files.LineLength
784	 * @phan-param array{lag?:int,since?:int,pending?:bool,lockTSE?:int,staleTTL?:int,creating?:bool,version?:int,walltime?:int|float} $opts
785	 * @note Options added in 1.28: staleTTL
786	 * @note Options added in 1.33: creating
787	 * @note Options added in 1.34: version, walltime
788	 * @return bool Success
789	 */
790	final public function set( $key, $value, $ttl = self::TTL_INDEFINITE, array $opts = [] ) {
791		$now = $this->getCurrentTime();
792		$lag = $opts['lag'] ?? 0;
793		$age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
794		$pending = $opts['pending'] ?? false;
795		$lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
796		$staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
797		$creating = $opts['creating'] ?? false;
798		$version = $opts['version'] ?? null;
799		$walltime = $opts['walltime'] ?? null;
800
801		if ( $ttl < 0 ) {
802			return true; // not cacheable
803		}
804
805		// Do not cache potentially uncommitted data as it might get rolled back
806		if ( $pending ) {
807			$this->logger->info(
808				'Rejected set() for {cachekey} due to pending writes.',
809				[ 'cachekey' => $key ]
810			);
811
812			return true; // no-op the write for being unsafe
813		}
814
815		// Check if there is a risk of caching (stale) data that predates the last delete()
816		// tombstone due to the tombstone having expired. If so, then the behavior should depend
817		// on whether the problem is specific to this regeneration attempt or systemically affects
818		// attempts to regenerate this key. For systemic cases, the cache writes should set a low
819		// TTL so that the value at least remains cacheable. For non-systemic cases, the cache
820		// write can simply be rejected.
821		if ( $age > self::MAX_READ_LAG ) {
822			// Case A: high snapshot lag
823			if ( $walltime === null ) {
824				// Case A0: high snapshot lag without regeneration wall time info.
825				// Probably systemic; use a low TTL to avoid stampedes/uncacheability.
826				$mitigated = 'snapshot lag';
827				$mitigationTTL = self::TTL_SECOND;
828			} elseif ( ( $age - $walltime ) > self::MAX_READ_LAG ) {
829				// Case A1: value regeneration during an already long-running transaction.
830				// Probably non-systemic; rely on a less problematic regeneration attempt.
831				$mitigated = 'snapshot lag (late regeneration)';
832				$mitigationTTL = self::TTL_UNCACHEABLE;
833			} else {
834				// Case A2: value regeneration takes a long time.
835				// Probably systemic; use a low TTL to avoid stampedes/uncacheability.
836				$mitigated = 'snapshot lag (high regeneration time)';
837				$mitigationTTL = self::TTL_SECOND;
838			}
839		} elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
840			// Case B: high replication lag without high snapshot lag
841			// Probably systemic; use a low TTL to avoid stampedes/uncacheability
842			$mitigated = 'replication lag';
843			$mitigationTTL = self::TTL_LAGGED;
844		} elseif ( ( $lag + $age ) > self::MAX_READ_LAG ) {
845			// Case C: medium length request with medium replication lag
846			// Probably non-systemic; rely on a less problematic regeneration attempt
847			$mitigated = 'read lag';
848			$mitigationTTL = self::TTL_UNCACHEABLE;
849		} else {
850			// New value generated with recent enough data
851			$mitigated = null;
852			$mitigationTTL = null;
853		}
854
855		if ( $mitigationTTL === self::TTL_UNCACHEABLE ) {
856			$this->logger->warning(
857				"Rejected set() for {cachekey} due to $mitigated.",
858				[ 'cachekey' => $key, 'lag' => $lag, 'age' => $age, 'walltime' => $walltime ]
859			);
860
861			return true; // no-op the write for being unsafe
862		}
863
864		// TTL to use in staleness checks (does not effect persistence layer TTL)
865		$logicalTTL = null;
866
867		if ( $mitigationTTL !== null ) {
868			// New value generated from data that is old enough to be risky
869			if ( $lockTSE >= 0 ) {
870				// Value will have the normal expiry but will be seen as stale sooner
871				$logicalTTL = min( $ttl ?: INF, $mitigationTTL );
872			} else {
873				// Value expires sooner (leaving enough TTL for preemptive refresh)
874				$ttl = min( $ttl ?: INF, max( $mitigationTTL, self::LOW_TTL ) );
875			}
876
877			$this->logger->warning(
878				"Lowered set() TTL for {cachekey} due to $mitigated.",
879				[ 'cachekey' => $key, 'lag' => $lag, 'age' => $age, 'walltime' => $walltime ]
880			);
881		}
882
883		// Wrap that value with time/TTL/version metadata
884		$wrapped = $this->wrap( $value, $logicalTTL ?: $ttl, $version, $now, $walltime );
885		$storeTTL = $ttl + $staleTTL;
886
887		if ( $creating ) {
888			$ok = $this->cache->add(
889				$this->makeSisterKey( $key, self::TYPE_VALUE ),
890				$wrapped,
891				$storeTTL
892			);
893		} else {
894			$ok = $this->cache->merge(
895				$this->makeSisterKey( $key, self::TYPE_VALUE ),
896				static function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
897					// A string value means that it is a tombstone; do nothing in that case
898					return ( is_string( $cWrapped ) ) ? false : $wrapped;
899				},
900				$storeTTL,
901				1 // 1 attempt
902			);
903		}
904
905		return $ok;
906	}
907
908	/**
909	 * Purge a key from all datacenters
910	 *
911	 * This should only be called when the underlying data (being cached)
912	 * changes in a significant way. This deletes the key and starts a hold-off
913	 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
914	 * This is done to avoid the following race condition:
915	 *   - a) Some DB data changes and delete() is called on a corresponding key
916	 *   - b) A request refills the key with a stale value from a lagged DB
917	 *   - c) The stale value is stuck there until the key is expired/evicted
918	 *
919	 * This is implemented by storing a special "tombstone" value at the cache
920	 * key that this class recognizes; get() calls will return false for the key
921	 * and any set() calls will refuse to replace tombstone values at the key.
922	 * For this to always avoid stale value writes, the following must hold:
923	 *   - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
924	 *   - b) If lag is higher, the DB will have gone into read-only mode already
925	 *
926	 * Note that set() can also be lag-aware and lower the TTL if it's high.
927	 *
928	 * Be aware that this does not clear the process cache. Even if it did, callbacks
929	 * used by getWithSetCallback() might still return stale data in the case of either
930	 * uncommitted or not-yet-replicated changes (callback generally use replica DBs).
931	 *
932	 * When using potentially long-running ACID transactions, a good pattern is
933	 * to use a pre-commit hook to issue the delete. This means that immediately
934	 * after commit, callers will see the tombstone in cache upon purge relay.
935	 * It also avoids the following race condition:
936	 *   - a) T1 begins, changes a row, and calls delete()
937	 *   - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
938	 *   - c) T2 starts, reads the row and calls set() due to a cache miss
939	 *   - d) T1 finally commits
940	 *   - e) Stale value is stuck in cache
941	 *
942	 * Example usage:
943	 * @code
944	 *     $dbw->startAtomic( __METHOD__ ); // start of request
945	 *     ... <execute some stuff> ...
946	 *     // Update the row in the DB
947	 *     $dbw->update( ... );
948	 *     $key = $cache->makeKey( 'homes', $homeId );
949	 *     // Purge the corresponding cache entry just before committing
950	 *     $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
951	 *         $cache->delete( $key );
952	 *     } );
953	 *     ... <execute some stuff> ...
954	 *     $dbw->endAtomic( __METHOD__ ); // end of request
955	 * @endcode
956	 *
957	 * The $ttl parameter can be used when purging values that have not actually changed
958	 * recently. For example, user-requested purges or cache cleanup scripts might not need
959	 * to invoke a hold-off period on cache backfills, so they can use HOLDOFF_TTL_NONE.
960	 *
961	 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
962	 *
963	 * If called twice on the same key, then the last hold-off TTL takes precedence. For
964	 * idempotence, the $ttl should not vary for different delete() calls on the same key.
965	 *
966	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
967	 * @param int $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
968	 * @return bool True if the item was purged or not found, false on failure
969	 */
970	final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
971		// Purge values must be stored under the value key so that WANObjectCache::set()
972		// can atomically merge values without accidentally undoing a recent purge and thus
973		// violating the holdoff TTL restriction.
974		$valueSisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE );
975
976		// When an on-host tier is configured, fetchKeys() relies on "flux" keys to determine
977		// whether a value from the on-host tier is still valid. A "flux" key is a short-lived
978		// key that contains the last recent purge due to delete(). This approach avoids having
979		// to purge the on-host cache service on potentially hundreds of application servers.
980
981		if ( $ttl <= 0 ) {
982			// A client or cache cleanup script is requesting a cache purge, so there is no
983			// volatility period due to replica DB lag. Any recent change to an entity cached
984			// in this key should have triggered an appropriate purge event.
985
986			// Remove the key from all datacenters, ignoring any on-host tier. Since on-host
987			// tier caches only use low key TTLs, setting "flux" keys here has little practical
988			// benefit; missed purges should be rare and the on-host tier will quickly correct
989			// itself in those rare cases.
990			$ok = $this->relayNonVolatilePurge( $valueSisterKey );
991		} else {
992			// A cacheable entity recently changed, so there might be a volatility period due
993			// to replica DB lag. Clients usually expect their actions to be reflected in any
994			// of their subsequent web request. This is attainable if (a) purge relay lag is
995			// lower than the time it takes for subsequent request by the client to arrive,
996			// and, (b) DB replica queries have "read-your-writes" consistency due to DB lag
997			// mitigation systems.
998
999			$now = $this->getCurrentTime();
1000			// Set the key to the purge value in all datacenters
1001			$purgeBySisterKey = [ $valueSisterKey => $this->makeTombstonePurgeValue( $now ) ];
1002			// When an on-host tier is configured, invalidate it by setting "flux" keys
1003			if ( $this->onHostRoute !== null ) {
1004				$fluxSisterKey = $this->makeSisterKey( $key, self::TYPE_FLUX );
1005				$purgeBySisterKey[$fluxSisterKey] = $this->makeTombstonePurgeValue( $now );
1006			}
1007
1008			$ok = $this->relayVolatilePurges( $purgeBySisterKey, $ttl );
1009		}
1010
1011		$kClass = $this->determineKeyClassForStats( $key );
1012		$this->stats->increment( "wanobjectcache.$kClass.delete." . ( $ok ? 'ok' : 'error' ) );
1013
1014		return $ok;
1015	}
1016
1017	/**
1018	 * Fetch the value of a timestamp "check" key
1019	 *
1020	 * The key will be *initialized* to the current time if not set,
1021	 * so only call this method if this behavior is actually desired
1022	 *
1023	 * The timestamp can be used to check whether a cached value is valid.
1024	 * Callers should not assume that this returns the same timestamp in
1025	 * all datacenters due to relay delays.
1026	 *
1027	 * The level of staleness can roughly be estimated from this key, but
1028	 * if the key was evicted from cache, such calculations may show the
1029	 * time since expiry as ~0 seconds.
1030	 *
1031	 * Note that "check" keys won't collide with other regular keys.
1032	 *
1033	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1034	 * @return float UNIX timestamp
1035	 */
1036	final public function getCheckKeyTime( $key ) {
1037		return $this->getMultiCheckKeyTime( [ $key ] )[$key];
1038	}
1039
1040	/**
1041	 * Fetch the values of each timestamp "check" key
1042	 *
1043	 * This works like getCheckKeyTime() except it takes a list of keys
1044	 * and returns a map of timestamps instead of just that of one key
1045	 *
1046	 * This might be useful if both:
1047	 *   - a) a class of entities each depend on hundreds of other entities
1048	 *   - b) these other entities are depended upon by millions of entities
1049	 *
1050	 * The later entities can each use a "check" key to invalidate their dependee entities.
1051	 * However, it is expensive for the former entities to verify against all of the relevant
1052	 * "check" keys during each getWithSetCallback() call. A less expensive approach is to do
1053	 * these verifications only after a "time-till-verify" (TTV) has passed. This is a middle
1054	 * ground between using blind TTLs and using constant verification. The adaptiveTTL() method
1055	 * can be used to dynamically adjust the TTV. Also, the initial TTV can make use of the
1056	 * last-modified times of the dependent entities (either from the DB or the "check" keys).
1057	 *
1058	 * Example usage:
1059	 * @code
1060	 *     $value = $cache->getWithSetCallback(
1061	 *         $cache->makeGlobalKey( 'wikibase-item', $id ),
1062	 *         self::INITIAL_TTV, // initial time-till-verify
1063	 *         function ( $oldValue, &$ttv, &$setOpts, $oldAsOf ) use ( $checkKeys, $cache ) {
1064	 *             $now = microtime( true );
1065	 *             // Use $oldValue if it passes max ultimate age and "check" key comparisons
1066	 *             if ( $oldValue &&
1067	 *                 $oldAsOf > max( $cache->getMultiCheckKeyTime( $checkKeys ) ) &&
1068	 *                 ( $now - $oldValue['ctime'] ) <= self::MAX_CACHE_AGE
1069	 *             ) {
1070	 *                 // Increase time-till-verify by 50% of last time to reduce overhead
1071	 *                 $ttv = $cache->adaptiveTTL( $oldAsOf, self::MAX_TTV, self::MIN_TTV, 1.5 );
1072	 *                 // Unlike $oldAsOf, "ctime" is the ultimate age of the cached data
1073	 *                 return $oldValue;
1074	 *             }
1075	 *
1076	 *             $mtimes = []; // dependency last-modified times; passed by reference
1077	 *             $value = [ 'data' => $this->fetchEntityData( $mtimes ), 'ctime' => $now ];
1078	 *             // Guess time-till-change among the dependencies, e.g. 1/(total change rate)
1079	 *             $ttc = 1 / array_sum( array_map(
1080	 *                 function ( $mtime ) use ( $now ) {
1081	 *                     return 1 / ( $mtime ? ( $now - $mtime ) : 900 );
1082	 *                 },
1083	 *                 $mtimes
1084	 *             ) );
1085	 *             // The time-to-verify should not be overly pessimistic nor optimistic
1086	 *             $ttv = min( max( $ttc, self::MIN_TTV ), self::MAX_TTV );
1087	 *
1088	 *             return $value;
1089	 *         },
1090	 *         [ 'staleTTL' => $cache::TTL_DAY ] // keep around to verify and re-save
1091	 *     );
1092	 * @endcode
1093	 *
1094	 * @see WANObjectCache::getCheckKeyTime()
1095	 * @see WANObjectCache::getWithSetCallback()
1096	 *
1097	 * @param string[] $keys Cache keys made with makeKey()/makeGlobalKey()
1098	 * @return float[] Map of (key => UNIX timestamp)
1099	 * @since 1.31
1100	 */
1101	final public function getMultiCheckKeyTime( array $keys ) {
1102		$checkSisterKeysByKey = [];
1103		foreach ( $keys as $key ) {
1104			$checkSisterKeysByKey[$key] = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1105		}
1106
1107		$wrappedBySisterKey = $this->cache->getMulti( $checkSisterKeysByKey );
1108		$wrappedBySisterKey += array_fill_keys( $checkSisterKeysByKey, false );
1109
1110		$times = [];
1111		foreach ( $checkSisterKeysByKey as $key => $checkSisterKey ) {
1112			$purge = $this->parsePurgeValue( $wrappedBySisterKey[$checkSisterKey] );
1113			if ( $purge !== false ) {
1114				$time = $purge[self::PURGE_TIME];
1115			} else {
1116				// Casting assures identical floats for the next getCheckKeyTime() calls
1117				$now = (string)$this->getCurrentTime();
1118				$this->cache->add(
1119					$checkSisterKey,
1120					$this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL ),
1121					self::CHECK_KEY_TTL
1122				);
1123				$time = (float)$now;
1124			}
1125
1126			$times[$key] = $time;
1127		}
1128
1129		return $times;
1130	}
1131
1132	/**
1133	 * Purge a "check" key from all datacenters, invalidating keys that use it
1134	 *
1135	 * This should only be called when the underlying data (being cached)
1136	 * changes in a significant way, and it is impractical to call delete()
1137	 * on all keys that should be changed. When get() is called on those
1138	 * keys, the relevant "check" keys must be supplied for this to work.
1139	 *
1140	 * The "check" key essentially represents a last-modified time of an entity.
1141	 * When the key is touched, the timestamp will be updated to the current time.
1142	 * Keys using the "check" key via get(), getMulti(), or getWithSetCallback() will
1143	 * be invalidated. This approach is useful if many keys depend on a single entity.
1144	 *
1145	 * The timestamp of the "check" key is treated as being HOLDOFF_TTL seconds in the
1146	 * future by get*() methods in order to avoid race conditions where keys are updated
1147	 * with stale values (e.g. from a lagged replica DB). A high TTL is set on the "check"
1148	 * key, making it possible to know the timestamp of the last change to the corresponding
1149	 * entities in most cases. This might use more cache space than resetCheckKey().
1150	 *
1151	 * When a few important keys get a large number of hits, a high cache time is usually
1152	 * desired as well as "lockTSE" logic. The resetCheckKey() method is less appropriate
1153	 * in such cases since the "time since expiry" cannot be inferred, causing any get()
1154	 * after the reset to treat the key as being "hot", resulting in more stale value usage.
1155	 *
1156	 * Note that "check" keys won't collide with other regular keys.
1157	 *
1158	 * @see WANObjectCache::get()
1159	 * @see WANObjectCache::getWithSetCallback()
1160	 * @see WANObjectCache::resetCheckKey()
1161	 *
1162	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1163	 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_TTL_NONE constant
1164	 * @return bool True if the item was purged or not found, false on failure
1165	 */
1166	final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
1167		$checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1168		$ok = $this->relayVolatilePurges(
1169			[ $checkSisterKey => $this->makeCheckPurgeValue( $this->getCurrentTime(), $holdoff ) ],
1170			self::CHECK_KEY_TTL
1171		);
1172
1173		$kClass = $this->determineKeyClassForStats( $key );
1174		$this->stats->increment( "wanobjectcache.$kClass.ck_touch." . ( $ok ? 'ok' : 'error' ) );
1175
1176		return $ok;
1177	}
1178
1179	/**
1180	 * Delete a "check" key from all datacenters, invalidating keys that use it
1181	 *
1182	 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
1183	 * or getWithSetCallback() will be invalidated. The differences are:
1184	 *   - a) The "check" key will be deleted from all caches and lazily
1185	 *        re-initialized when accessed (rather than set everywhere)
1186	 *   - b) Thus, dependent keys will be known to be stale, but not
1187	 *        for how long (they are treated as "just" purged), which
1188	 *        effects any lockTSE logic in getWithSetCallback()
1189	 *   - c) Since "check" keys are initialized only on the server the key hashes
1190	 *        to, any temporary ejection of that server will cause the value to be
1191	 *        seen as purged as a new server will initialize the "check" key.
1192	 *
1193	 * The advantage here is that the "check" keys, which have high TTLs, will only
1194	 * be created when a get*() method actually uses that key. This is better when
1195	 * a large number of "check" keys are invalided in a short period of time.
1196	 *
1197	 * Note that "check" keys won't collide with other regular keys.
1198	 *
1199	 * @see WANObjectCache::get()
1200	 * @see WANObjectCache::getWithSetCallback()
1201	 * @see WANObjectCache::touchCheckKey()
1202	 *
1203	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1204	 * @return bool True if the item was purged or not found, false on failure
1205	 */
1206	final public function resetCheckKey( $key ) {
1207		$checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1208		$ok = $this->relayNonVolatilePurge( $checkSisterKey );
1209
1210		$kClass = $this->determineKeyClassForStats( $key );
1211		$this->stats->increment( "wanobjectcache.$kClass.ck_reset." . ( $ok ? 'ok' : 'error' ) );
1212
1213		return $ok;
1214	}
1215
1216	/**
1217	 * Method to fetch/regenerate a cache key
1218	 *
1219	 * On cache miss, the key will be set to the callback result via set()
1220	 * (unless the callback returns false) and that result will be returned.
1221	 * The arguments supplied to the callback are:
1222	 *   - $oldValue: prior cache value or false if none was present
1223	 *   - &$ttl: alterable reference to the TTL to be assigned to the new value
1224	 *   - &$setOpts: alterable reference to the set() options to be used with the new value
1225	 *   - $oldAsOf: generation UNIX timestamp of $oldValue or null if not present (since 1.28)
1226	 *   - $params: custom field/value map as defined by $cbParams (since 1.35)
1227	 *
1228	 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
1229	 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
1230	 * value, but it can be used to maintain "most recent X" values that come from time or
1231	 * sequence based source data, provided that the "as of" id/time is tracked. Note that
1232	 * preemptive regeneration and $checkKeys can result in a non-false current value.
1233	 *
1234	 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
1235	 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
1236	 * regeneration will automatically be triggered using the callback.
1237	 *
1238	 * The $ttl argument and "hotTTR" option (in $opts) use time-dependent randomization
1239	 * to avoid stampedes. Keys that are slow to regenerate and either heavily used
1240	 * or subject to explicit (unpredictable) purges, may need additional mechanisms.
1241	 * The simplest way to avoid stampedes for such keys is to use 'lockTSE' (in $opts).
1242	 * If explicit purges are needed, also:
1243	 *   - a) Pass $key into $checkKeys
1244	 *   - b) Use touchCheckKey( $key ) instead of delete( $key )
1245	 *
1246	 * This applies cache server I/O stampede protection against duplicate cache sets.
1247	 * This is important when the callback is slow and/or yields large values for a key.
1248	 *
1249	 * Example usage (typical key):
1250	 * @code
1251	 *     $catInfo = $cache->getWithSetCallback(
1252	 *         // Key to store the cached value under
1253	 *         $cache->makeKey( 'cat-attributes', $catId ),
1254	 *         // Time-to-live (in seconds)
1255	 *         $cache::TTL_MINUTE,
1256	 *         // Function that derives the new key value
1257	 *         function ( $oldValue, &$ttl, array &$setOpts ) {
1258	 *             $dbr = wfGetDB( DB_REPLICA );
1259	 *             // Account for any snapshot/replica DB lag
1260	 *             $setOpts += Database::getCacheSetOptions( $dbr );
1261	 *
1262	 *             return $dbr->selectRow( ... );
1263	 *        }
1264	 *     );
1265	 * @endcode
1266	 *
1267	 * Example usage (key that is expensive and hot):
1268	 * @code
1269	 *     $catConfig = $cache->getWithSetCallback(
1270	 *         // Key to store the cached value under
1271	 *         $cache->makeKey( 'site-cat-config' ),
1272	 *         // Time-to-live (in seconds)
1273	 *         $cache::TTL_DAY,
1274	 *         // Function that derives the new key value
1275	 *         function ( $oldValue, &$ttl, array &$setOpts ) {
1276	 *             $dbr = wfGetDB( DB_REPLICA );
1277	 *             // Account for any snapshot/replica DB lag
1278	 *             $setOpts += Database::getCacheSetOptions( $dbr );
1279	 *
1280	 *             return CatConfig::newFromRow( $dbr->selectRow( ... ) );
1281	 *         },
1282	 *         [
1283	 *             // Calling touchCheckKey() on this key invalidates the cache
1284	 *             'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
1285	 *             // Try to only let one datacenter thread manage cache updates at a time
1286	 *             'lockTSE' => 30,
1287	 *             // Avoid querying cache servers multiple times in a web request
1288	 *             'pcTTL' => $cache::TTL_PROC_LONG
1289	 *         ]
1290	 *     );
1291	 * @endcode
1292	 *
1293	 * Example usage (key with dynamic dependencies):
1294	 * @code
1295	 *     $catState = $cache->getWithSetCallback(
1296	 *         // Key to store the cached value under
1297	 *         $cache->makeKey( 'cat-state', $cat->getId() ),
1298	 *         // Time-to-live (seconds)
1299	 *         $cache::TTL_HOUR,
1300	 *         // Function that derives the new key value
1301	 *         function ( $oldValue, &$ttl, array &$setOpts ) {
1302	 *             // Determine new value from the DB
1303	 *             $dbr = wfGetDB( DB_REPLICA );
1304	 *             // Account for any snapshot/replica DB lag
1305	 *             $setOpts += Database::getCacheSetOptions( $dbr );
1306	 *
1307	 *             return CatState::newFromResults( $dbr->select( ... ) );
1308	 *         },
1309	 *         [
1310	 *              // The "check" keys that represent things the value depends on;
1311	 *              // Calling touchCheckKey() on any of them invalidates the cache
1312	 *             'checkKeys' => [
1313	 *                 $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
1314	 *                 $cache->makeKey( 'people-present', $cat->getHouseId() ),
1315	 *                 $cache->makeKey( 'cat-laws', $cat->getCityId() ),
1316	 *             ]
1317	 *         ]
1318	 *     );
1319	 * @endcode
1320	 *
1321	 * Example usage (key that is expensive with too many DB dependencies for "check" keys):
1322	 * @code
1323	 *     $catToys = $cache->getWithSetCallback(
1324	 *         // Key to store the cached value under
1325	 *         $cache->makeKey( 'cat-toys', $catId ),
1326	 *         // Time-to-live (seconds)
1327	 *         $cache::TTL_HOUR,
1328	 *         // Function that derives the new key value
1329	 *         function ( $oldValue, &$ttl, array &$setOpts ) {
1330	 *             // Determine new value from the DB
1331	 *             $dbr = wfGetDB( DB_REPLICA );
1332	 *             // Account for any snapshot/replica DB lag
1333	 *             $setOpts += Database::getCacheSetOptions( $dbr );
1334	 *
1335	 *             return CatToys::newFromResults( $dbr->select( ... ) );
1336	 *         },
1337	 *         [
1338	 *              // Get the highest timestamp of any of the cat's toys
1339	 *             'touchedCallback' => function ( $value ) use ( $catId ) {
1340	 *                 $dbr = wfGetDB( DB_REPLICA );
1341	 *                 $ts = $dbr->selectField( 'cat_toys', 'MAX(ct_touched)', ... );
1342	 *
1343	 *                 return wfTimestampOrNull( TS_UNIX, $ts );
1344	 *             },
1345	 *             // Avoid DB queries for repeated access
1346	 *             'pcTTL' => $cache::TTL_PROC_SHORT
1347	 *         ]
1348	 *     );
1349	 * @endcode
1350	 *
1351	 * Example usage (hot key holding most recent 100 events):
1352	 * @code
1353	 *     $lastCatActions = $cache->getWithSetCallback(
1354	 *         // Key to store the cached value under
1355	 *         $cache->makeKey( 'cat-last-actions', 100 ),
1356	 *         // Time-to-live (in seconds)
1357	 *         10,
1358	 *         // Function that derives the new key value
1359	 *         function ( $oldValue, &$ttl, array &$setOpts ) {
1360	 *             $dbr = wfGetDB( DB_REPLICA );
1361	 *             // Account for any snapshot/replica DB lag
1362	 *             $setOpts += Database::getCacheSetOptions( $dbr );
1363	 *
1364	 *             // Start off with the last cached list
1365	 *             $list = $oldValue ?: [];
1366	 *             // Fetch the last 100 relevant rows in descending order;
1367	 *             // only fetch rows newer than $list[0] to reduce scanning
1368	 *             $rows = iterator_to_array( $dbr->select( ... ) );
1369	 *             // Merge them and get the new "last 100" rows
1370	 *             return array_slice( array_merge( $new, $list ), 0, 100 );
1371	 *        },
1372	 *        [
1373	 *             // Try to only let one datacenter thread manage cache updates at a time
1374	 *             'lockTSE' => 30,
1375	 *             // Use a magic value when no cache value is ready rather than stampeding
1376	 *             'busyValue' => 'computing'
1377	 *        ]
1378	 *     );
1379	 * @endcode
1380	 *
1381	 * Example usage (key holding an LRU subkey:value map; this can avoid flooding cache with
1382	 * keys for an unlimited set of (constraint,situation) pairs, thereby avoiding elevated
1383	 * cache evictions and wasted memory):
1384	 * @code
1385	 *     $catSituationTolerabilityCache = $this->cache->getWithSetCallback(
1386	 *         // Group by constraint ID/hash, cat family ID/hash, or something else useful
1387	 *         $this->cache->makeKey( 'cat-situation-tolerability-checks', $groupKey ),
1388	 *         WANObjectCache::TTL_DAY, // rarely used groups should fade away
1389	 *         // The $scenarioKey format is $constraintId:<ID/hash of $situation>
1390	 *         function ( $cacheMap ) use ( $scenarioKey, $constraintId, $situation ) {
1391	 *             $lruCache = MapCacheLRU::newFromArray( $cacheMap ?: [], self::CACHE_SIZE );
1392	 *             $result = $lruCache->get( $scenarioKey ); // triggers LRU bump if present
1393	 *             if ( $result === null || $this->isScenarioResultExpired( $result ) ) {
1394	 *                 $result = $this->checkScenarioTolerability( $constraintId, $situation );
1395	 *                 $lruCache->set( $scenarioKey, $result, 3 / 8 );
1396	 *             }
1397	 *             // Save the new LRU cache map and reset the map's TTL
1398	 *             return $lruCache->toArray();
1399	 *         },
1400	 *         [
1401	 *             // Once map is > 1 sec old, consider refreshing
1402	 *             'ageNew' => 1,
1403	 *             // Update within 5 seconds after "ageNew" given a 1hz cache check rate
1404	 *             'hotTTR' => 5,
1405	 *             // Avoid querying cache servers multiple times in a request; this also means
1406	 *             // that a request can only alter the value of any given constraint key once
1407	 *             'pcTTL' => WANObjectCache::TTL_PROC_LONG
1408	 *         ]
1409	 *     );
1410	 *     $tolerability = isset( $catSituationTolerabilityCache[$scenarioKey] )
1411	 *         ? $catSituationTolerabilityCache[$scenarioKey]
1412	 *         : $this->checkScenarioTolerability( $constraintId, $situation );
1413	 * @endcode
1414	 *
1415	 * @see WANObjectCache::get()
1416	 * @see WANObjectCache::set()
1417	 *
1418	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1419	 * @param int $ttl Nominal seconds-to-live for newly computed values. Special values are:
1420	 *   - WANObjectCache::TTL_INDEFINITE: Cache forever (subject to LRU-style evictions)
1421	 *   - WANObjectCache::TTL_UNCACHEABLE: Do not cache (if the key exists, it is not deleted)
1422	 * @param callable $callback Value generation function
1423	 * @param array $opts Options map:
1424	 *   - checkKeys: List of "check" keys. The key at $key will be seen as stale when either
1425	 *      touchCheckKey() or resetCheckKey() is called on any of the keys in this list. This
1426	 *      is useful if thousands or millions of keys depend on the same entity. The entity can
1427	 *      simply have its "check" key updated whenever the entity is modified.
1428	 *      Default: [].
1429	 *   - graceTTL: If the key is invalidated (by "checkKeys" or "touchedCallback") less than
1430	 *      this many seconds ago, consider reusing the stale value. The odds of a refresh become
1431	 *      more likely over time, becoming certain once the grace period is reached. This can
1432	 *      reduce traffic spikes when millions of keys are compared to the same "check" key and
1433	 *      touchCheckKey() or resetCheckKey() is called on that "check" key. This option is not
1434	 *      useful for avoiding traffic spikes in the case of the key simply expiring on account
1435	 *      of its TTL (use "lowTTL" instead).
1436	 *      Default: WANObjectCache::GRACE_TTL_NONE.
1437	 *   - lockTSE: Prefer the use of a mutex during value regeneration of the key if its TSE
1438	 *      ("time since expiry") is less than the given number of seconds ago. The TSE is
1439	 *      influenced by deletion, invalidation (e.g. by "checkKeys" or "touchedCallback"),
1440	 *      and various other options (e.g. "staleTTL"). A low enough TSE is assumed to indicate
1441	 *      a high enough key access rate to justify stampede avoidance. A thread that tries and
1442	 *      fails to acquire the mutex will use a stale value for the key, if there is one, and,
1443	 *      if not, it will execute the callback. Note that no cache value exists after deletion
1444	 *      or storage-layer expiration/eviction; to prevent stampedes during these cases, avoid
1445	 *      using delete(), keep "lowTTL" enabled, and consider using "busyValue".
1446	 *      Default: WANObjectCache::TSE_NONE.
1447	 *   - busyValue: Specify a placeholder value to use when no value exists and another thread
1448	 *      is currently regenerating it. This assures that cache stampedes cannot happen if the
1449	 *      value falls out of cache. This also mitigates stampedes when value regeneration
1450	 *      becomes very slow (greater than $ttl/"lowTTL"). If this is a closure, then it will
1451	 *      be invoked to get the placeholder when needed.
1452	 *      Default: null.
1453	 *   - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
1454	 *      network I/O when a key is read several times. This will not cache when the callback
1455	 *      returns false, however. Note that any purges will not be seen while process cached;
1456	 *      since the callback should use replica DBs and they may be lagged or have snapshot
1457	 *      isolation anyway, this should not typically matter.
1458	 *      Default: WANObjectCache::TTL_UNCACHEABLE.
1459	 *   - pcGroup: Process cache group to use instead of the primary one. If set, this must be
1460	 *      of the format ALPHANUMERIC_NAME:MAX_KEY_SIZE, e.g. "mydata:10". Use this for storing
1461	 *      large values, small yet numerous values, or some values with a high cost of eviction.
1462	 *      It is generally preferable to use a class constant when setting this value.
1463	 *      This has no effect unless pcTTL is used.
1464	 *      Default: WANObjectCache::PC_PRIMARY.
1465	 *   - version: Integer version number. This lets callers make breaking changes to the format
1466	 *      of cached values without causing problems for sites that use non-instantaneous code
1467	 *      deployments. Old and new code will recognize incompatible versions and purges from
1468	 *      both old and new code will been seen by each other. When this method encounters an
1469	 *      incompatibly versioned value at the provided key, a "variant key" will be used for
1470	 *      reading from and saving to cache. The variant key is specific to the key and version
1471	 *      number provided to this method. If the variant key value is older than that of the
1472	 *      provided key, or the provided key is non-existant, then the variant key will be seen
1473	 *      as non-existant. Therefore, delete() calls invalidate the provided key's variant keys.
1474	 *      The "checkKeys" and "touchedCallback" options still apply to variant keys as usual.
1475	 *      Avoid storing class objects, as this reduces compatibility (due to serialization).
1476	 *      Default: null.
1477	 *   - minAsOf: Reject values if they were generated before this UNIX timestamp.
1478	 *      This is useful if the source of a key is suspected of having possibly changed
1479	 *      recently, and the caller wants any such changes to be reflected.
1480	 *      Default: WANObjectCache::MIN_TIMESTAMP_NONE.
1481	 *   - hotTTR: Expected time-till-refresh (TTR) in seconds for keys that average ~1 hit per
1482	 *      second (e.g. 1Hz). Keys with a hit rate higher than 1Hz will refresh sooner than this
1483	 *      TTR and vise versa. Such refreshes won't happen until keys are "ageNew" seconds old.
1484	 *      This uses randomization to avoid triggering cache stampedes. The TTR is useful at
1485	 *      reducing the impact of missed cache purges, since the effect of a heavily referenced
1486	 *      key being stale is worse than that of a rarely referenced key. Unlike simply lowering
1487	 *      $ttl, seldomly used keys are largely unaffected by this option, which makes it
1488	 *      possible to have a high hit rate for the "long-tail" of less-used keys.
1489	 *      Default: WANObjectCache::HOT_TTR.
1490	 *   - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
1491	 *      than this. It becomes more likely over time, becoming certain once the key is expired.
1492	 *      This helps avoid cache stampedes that might be triggered due to the key expiring.
1493	 *      Default: WANObjectCache::LOW_TTL.
1494	 *   - ageNew: Consider popularity refreshes only once a key reaches this age in seconds.
1495	 *      Default: WANObjectCache::AGE_NEW.
1496	 *   - staleTTL: Seconds to keep the key around if it is stale. This means that on cache
1497	 *      miss the callback may get $oldValue/$oldAsOf values for keys that have already been
1498	 *      expired for this specified time. This is useful if adaptiveTTL() is used on the old
1499	 *      value's as-of time when it is verified as still being correct.
1500	 *      Default: WANObjectCache::STALE_TTL_NONE
1501	 *   - touchedCallback: A callback that takes the current value and returns a UNIX timestamp
1502	 *      indicating the last time a dynamic dependency changed. Null can be returned if there
1503	 *      are no relevant dependency changes to check. This can be used to check against things
1504	 *      like last-modified times of files or DB timestamp fields. This should generally not be
1505	 *      used for small and easily queried values in a DB if the callback itself ends up doing
1506	 *      a similarly expensive DB query to check a timestamp. Usages of this option makes the
1507	 *      most sense for values that are moderately to highly expensive to regenerate and easy
1508	 *      to query for dependency timestamps. The use of "pcTTL" reduces timestamp queries.
1509	 *      Default: null.
1510	 * @param array $cbParams Custom field/value map to pass to the callback (since 1.35)
1511	 * @phpcs:ignore Generic.Files.LineLength
1512	 * @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
1513	 * @return mixed Value found or written to the key
1514	 * @note Options added in 1.28: version, busyValue, hotTTR, ageNew, pcGroup, minAsOf
1515	 * @note Options added in 1.31: staleTTL, graceTTL
1516	 * @note Options added in 1.33: touchedCallback
1517	 * @note Callable type hints are not used to avoid class-autoloading
1518	 */
1519	final public function getWithSetCallback(
1520		$key, $ttl, $callback, array $opts = [], array $cbParams = []
1521	) {
1522		$version = $opts['version'] ?? null;
1523		$pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
1524		$pCache = ( $pcTTL >= 0 )
1525			? $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY )
1526			: null;
1527
1528		// Use the process cache if requested as long as no outer cache callback is running.
1529		// Nested callback process cache use is not lag-safe with regard to HOLDOFF_TTL since
1530		// process cached values are more lagged than persistent ones as they are not purged.
1531		if ( $pCache && $this->callbackDepth == 0 ) {
1532			$cached = $pCache->get( $this->getProcessCacheKey( $key, $version ), $pcTTL, false );
1533			if ( $cached !== false ) {
1534				$this->logger->debug( "getWithSetCallback($key): process cache hit" );
1535				return $cached;
1536			}
1537		}
1538
1539		$res = $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams );
1540		list( $value, $valueVersion, $curAsOf ) = $res;
1541		if ( $valueVersion !== $version ) {
1542			// Current value has a different version; use the variant key for this version.
1543			// Regenerate the variant value if it is not newer than the main value at $key
1544			// so that purges to the main key propagate to the variant value.
1545			$this->logger->debug( "getWithSetCallback($key): using variant key" );
1546			list( $value ) = $this->fetchOrRegenerate(
1547				$this->makeGlobalKey( 'WANCache-key-variant', md5( $key ), $version ),
1548				$ttl,
1549				$callback,
1550				[ 'version' => null, 'minAsOf' => $curAsOf ] + $opts,
1551				$cbParams
1552			);
1553		}
1554
1555		// Update the process cache if enabled
1556		if ( $pCache && $value !== false ) {
1557			$pCache->set( $this->getProcessCacheKey( $key, $version ), $value );
1558		}
1559
1560		return $value;
1561	}
1562
1563	/**
1564	 * Do the actual I/O for getWithSetCallback() when needed
1565	 *
1566	 * @see WANObjectCache::getWithSetCallback()
1567	 *
1568	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1569	 * @param int $ttl
1570	 * @param callable $callback
1571	 * @param array $opts
1572	 * @param array $cbParams
1573	 * @return array Ordered list of the following:
1574	 *   - Cached or regenerated value
1575	 *   - Cached or regenerated value version number or null if not versioned
1576	 *   - Timestamp of the current cached value at the key or null if there is no value
1577	 * @note Callable type hints are not used to avoid class-autoloading
1578	 */
1579	private function fetchOrRegenerate( $key, $ttl, $callback, array $opts, array $cbParams ) {
1580		$checkKeys = $opts['checkKeys'] ?? [];
1581		$graceTTL = $opts['graceTTL'] ?? self::GRACE_TTL_NONE;
1582		$minAsOf = $opts['minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
1583		$hotTTR = $opts['hotTTR'] ?? self::HOT_TTR;
1584		$lowTTL = $opts['lowTTL'] ?? min( self::LOW_TTL, $ttl );
1585		$ageNew = $opts['ageNew'] ?? self::AGE_NEW;
1586		$touchedCb = $opts['touchedCallback'] ?? null;
1587		$initialTime = $this->getCurrentTime();
1588
1589		$kClass = $this->determineKeyClassForStats( $key );
1590
1591		// Get the current key value and its metadata
1592		$res = $this->fetchKeys( [ $key ], $checkKeys )[$key];
1593		$curValue = $res[self::RES_VALUE];
1594		$curInfo = $res[self::RES_METADATA];
1595		$curTTL = $curInfo[self::KEY_CUR_TTL];
1596		// Apply any $touchedCb invalidation timestamp to get the "last purge timestamp"
1597		list( $curTTL, $LPT ) = $this->resolveCTL( $curValue, $curTTL, $curInfo, $touchedCb );
1598		// Use the cached value if it exists and is not due for synchronous regeneration
1599		if (
1600			$this->isValid( $curValue, $curInfo[self::KEY_AS_OF], $minAsOf ) &&
1601			$this->isAliveOrInGracePeriod( $curTTL, $graceTTL )
1602		) {
1603			$preemptiveRefresh = (
1604				$this->worthRefreshExpiring( $curTTL, $curInfo[self::KEY_TTL], $lowTTL ) ||
1605				$this->worthRefreshPopular( $curInfo['asOf'], $ageNew, $hotTTR, $initialTime )
1606			);
1607			if ( !$preemptiveRefresh ) {
1608				$this->stats->timing(
1609					"wanobjectcache.$kClass.hit.good",
1610					1e3 * ( $this->getCurrentTime() - $initialTime )
1611				);
1612
1613				return [ $curValue, $curInfo[self::KEY_VERSION], $curInfo[self::KEY_AS_OF] ];
1614			} elseif ( $this->scheduleAsyncRefresh( $key, $ttl, $callback, $opts, $cbParams ) ) {
1615				$this->logger->debug( "fetchOrRegenerate($key): hit with async refresh" );
1616				$this->stats->timing(
1617					"wanobjectcache.$kClass.hit.refresh",
1618					1e3 * ( $this->getCurrentTime() - $initialTime )
1619				);
1620
1621				return [ $curValue, $curInfo[self::KEY_VERSION], $curInfo[self::KEY_AS_OF] ];
1622			} else {
1623				$this->logger->debug( "fetchOrRegenerate($key): hit with sync refresh" );
1624			}
1625		}
1626
1627		// Determine if there is stale or volatile cached value that is still usable
1628		$isKeyTombstoned = ( $curInfo[self::KEY_TOMB_AS_OF] !== null );
1629		if ( $isKeyTombstoned ) {
1630			// Key is write-holed; use the (volatile) interim key as an alternative
1631			list( $possValue, $possInfo ) = $this->getInterimValue( $key, $minAsOf );
1632			// Update the "last purge time" since the $touchedCb timestamp depends on $value
1633			$LPT = $this->resolveTouched( $possValue, $LPT, $touchedCb );
1634		} else {
1635			$possValue = $curValue;
1636			$possInfo = $curInfo;
1637		}
1638
1639		// Avoid overhead from callback runs, regeneration locks, and cache sets during
1640		// hold-off periods for the key by reusing very recently generated cached values
1641		if (
1642			$this->isValid( $possValue, $possInfo[self::KEY_AS_OF], $minAsOf, $LPT ) &&
1643			$this->isVolatileValueAgeNegligible( $initialTime - $possInfo[self::KEY_AS_OF] )
1644		) {
1645			$this->logger->debug( "fetchOrRegenerate($key): volatile hit" );
1646			$this->stats->timing(
1647				"wanobjectcache.$kClass.hit.volatile",
1648				1e3 * ( $this->getCurrentTime() - $initialTime )
1649			);
1650
1651			return [ $possValue, $possInfo[self::KEY_VERSION], $curInfo[self::KEY_AS_OF] ];
1652		}
1653
1654		$lockTSE = $opts['lockTSE'] ?? self::TSE_NONE;
1655		$busyValue = $opts['busyValue'] ?? null;
1656		$staleTTL = $opts['staleTTL'] ?? self::STALE_TTL_NONE;
1657		$version = $opts['version'] ?? null;
1658
1659		// Determine whether one thread per datacenter should handle regeneration at a time
1660		$useRegenerationLock =
1661			// Note that since tombstones no-op set(), $lockTSE and $curTTL cannot be used to
1662			// deduce the key hotness because |$curTTL| will always keep increasing until the
1663			// tombstone expires or is overwritten by a new tombstone. Also, even if $lockTSE
1664			// is not set, constant regeneration of a key for the tombstone lifetime might be
1665			// very expensive. Assume tombstoned keys are possibly hot in order to reduce
1666			// the risk of high regeneration load after the delete() method is called.
1667			$isKeyTombstoned ||
1668			// Assume a key is hot if requested soon ($lockTSE seconds) after invalidation.
1669			// This avoids stampedes when timestamps from $checkKeys/$touchedCb bump.
1670			( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE ) ||
1671			// Assume a key is hot if there is no value and a busy fallback is given.
1672			// This avoids stampedes on eviction or preemptive regeneration taking too long.
1673			( $busyValue !== null && $possValue === false );
1674
1675		// If a regeneration lock is required, threads that do not get the lock will try to use
1676		// the stale value, the interim value, or the $busyValue placeholder, in that order. If
1677		// none of those are set then all threads will bypass the lock and regenerate the value.
1678		$hasLock = $useRegenerationLock && $this->claimStampedeLock( $key );
1679		if ( $useRegenerationLock && !$hasLock ) {
1680			if ( $this->isValid( $possValue, $possInfo[self::KEY_AS_OF], $minAsOf ) ) {
1681				$this->logger->debug( "fetchOrRegenerate($key): returning stale value" );
1682				$this->stats->timing(
1683					"wanobjectcache.$kClass.hit.stale",
1684					1e3 * ( $this->getCurrentTime() - $initialTime )
1685				);
1686
1687				return [ $possValue, $possInfo[self::KEY_VERSION], $curInfo[self::KEY_AS_OF] ];
1688			} elseif ( $busyValue !== null ) {
1689				$miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1690				$this->logger->debug( "fetchOrRegenerate($key): busy $miss" );
1691				$this->stats->timing(
1692					"wanobjectcache.$kClass.$miss.busy",
1693					1e3 * ( $this->getCurrentTime() - $initialTime )
1694				);
1695				$placeholderValue = $this->resolveBusyValue( $busyValue );
1696
1697				return [ $placeholderValue, $version, $curInfo[self::KEY_AS_OF] ];
1698			}
1699		}
1700
1701		// Generate the new value given any prior value with a matching version
1702		$setOpts = [];
1703		$preCallbackTime = $this->getCurrentTime();
1704		++$this->callbackDepth;
1705		try {
1706			$value = $callback(
1707				( $curInfo[self::KEY_VERSION] === $version ) ? $curValue : false,
1708				$ttl,
1709				$setOpts,
1710				( $curInfo[self::KEY_VERSION] === $version ) ? $curInfo[self::KEY_AS_OF] : null,
1711				$cbParams
1712			);
1713		} finally {
1714			--$this->callbackDepth;
1715		}
1716		$postCallbackTime = $this->getCurrentTime();
1717
1718		// How long it took to fetch, validate, and generate the value
1719		$elapsed = max( $postCallbackTime - $initialTime, 0.0 );
1720
1721		// Attempt to save the newly generated value if applicable
1722		if (
1723			// Callback yielded a cacheable value
1724			( $value !== false && $ttl >= 0 ) &&
1725			// Current thread was not raced out of a regeneration lock or key is tombstoned
1726			( !$useRegenerationLock || $hasLock || $isKeyTombstoned ) &&
1727			// Key does not appear to be undergoing a set() stampede
1728			$this->checkAndSetCooloff( $key, $kClass, $value, $elapsed, $hasLock )
1729		) {
1730			// How long it took to generate the value
1731			$walltime = max( $postCallbackTime - $preCallbackTime, 0.0 );
1732			$this->stats->timing( "wanobjectcache.$kClass.regen_walltime", 1e3 * $walltime );
1733			// If the key is write-holed then use the (volatile) interim key as an alternative
1734			if ( $isKeyTombstoned ) {
1735				$this->setInterimValue( $key, $value, $lockTSE, $version, $walltime );
1736			} else {
1737				$finalSetOpts = [
1738					// @phan-suppress-next-line PhanUselessBinaryAddRight
1739					'since' => $setOpts['since'] ?? $preCallbackTime,
1740					'version' => $version,
1741					'staleTTL' => $staleTTL,
1742					'lockTSE' => $lockTSE, // informs lag vs performance trade-offs
1743					'creating' => ( $curValue === false ), // optimization
1744					'walltime' => $walltime
1745				] + $setOpts;
1746				$this->set( $key, $value, $ttl, $finalSetOpts );
1747			}
1748		}
1749
1750		$this->yieldStampedeLock( $key, $hasLock );
1751
1752		$miss = is_infinite( $minAsOf ) ? 'renew' : 'miss';
1753		$this->logger->debug( "fetchOrRegenerate($key): $miss, new value computed" );
1754		$this->stats->timing(
1755			"wanobjectcache.$kClass.$miss.compute",
1756			1e3 * ( $this->getCurrentTime() - $initialTime )
1757		);
1758
1759		return [ $value, $version, $curInfo[self::KEY_AS_OF] ];
1760	}
1761
1762	/**
1763	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1764	 * @return bool Success
1765	 */
1766	private function claimStampedeLock( $key ) {
1767		$checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX );
1768		// Note that locking is not bypassed due to I/O errors; this avoids stampedes
1769		return $this->cache->add( $checkSisterKey, 1, self::LOCK_TTL );
1770	}
1771
1772	/**
1773	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1774	 * @param bool $hasLock
1775	 */
1776	private function yieldStampedeLock( $key, $hasLock ) {
1777		if ( $hasLock ) {
1778			$checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX );
1779			// The backend might be a mcrouter proxy set to broadcast DELETE to *all* the local
1780			// datacenter cache servers via OperationSelectorRoute (for increased consistency).
1781			// Since that would be excessive for these locks, use TOUCH to expire the key.
1782			$this->cache->changeTTL( $checkSisterKey, $this->getCurrentTime() - 60 );
1783		}
1784	}
1785
1786	/**
1787	 * Get sister keys that should be collocated with their corresponding base cache keys
1788	 *
1789	 * The key will bear the WANCache prefix and use the configured coalescing scheme
1790	 *
1791	 * @param string[] $baseKeys Cache keys made with makeKey()/makeGlobalKey()
1792	 * @param string $type Consistent hashing agnostic suffix character matching [a-zA-Z]
1793	 * @param string|null $route Routing prefix (optional)
1794	 * @return string[] Order-corresponding list of sister keys
1795	 */
1796	private function makeSisterKeys( array $baseKeys, string $type, string $route = null ) {
1797		$sisterKeys = [];
1798		foreach ( $baseKeys as $baseKey ) {
1799			$sisterKeys[] = $this->makeSisterKey( $baseKey, $type, $route );
1800		}
1801
1802		return $sisterKeys;
1803	}
1804
1805	/**
1806	 * Get a sister key that should be collocated with a base cache key
1807	 *
1808	 * The keys will bear the WANCache prefix and use the configured coalescing scheme
1809	 *
1810	 * @param string $baseKey Cache key made with makeKey()/makeGlobalKey()
1811	 * @param string $typeChar Consistent hashing agnostic suffix character matching [a-zA-Z]
1812	 * @param string|null $route Routing prefix (optional)
1813	 * @return string Sister key
1814	 */
1815	private function makeSisterKey( string $baseKey, string $typeChar, string $route = null ) {
1816		if ( $this->coalesceScheme === self::SCHEME_HASH_STOP ) {
1817			// Key style: "WANCache:<base key>|#|<character>"
1818			$sisterKey = 'WANCache:' . $baseKey . '|#|' . $typeChar;
1819		} else {
1820			// Key style: "WANCache:{<base key>}:<character>"
1821			$sisterKey = 'WANCache:{' . $baseKey . '}:' . $typeChar;
1822		}
1823
1824		if ( $route !== null ) {
1825			$sisterKey = $this->prependRoute( $sisterKey, $route );
1826		}
1827
1828		return $sisterKey;
1829	}
1830
1831	/**
1832	 * @param string $sisterKey Sister key from makeSisterKey()
1833	 * @return string Key collection name
1834	 * @internal For use by WANObjectCache/BagOStuff only
1835	 * @since 1.36
1836	 */
1837	public static function getCollectionFromSisterKey( string $sisterKey ) {
1838		if ( substr( $sisterKey, -4 ) === '|#|v' ) {
1839			// Key style: "WANCache:<base key>|#|<character>"
1840			$collection = substr( $sisterKey, 9, strcspn( $sisterKey, ':|', 9 ) );
1841		} elseif ( substr( $sisterKey, -3 ) === '}:v' ) {
1842			// Key style: "WANCache:{<base key>}:<character>"
1843			$collection = substr( $sisterKey, 10, strcspn( $sisterKey, ':}', 10 ) );
1844		} else {
1845			$collection = 'internal';
1846		}
1847
1848		return $collection;
1849	}
1850
1851	/**
1852	 * @param float $age Age of volatile/interim key in seconds
1853	 * @return bool Whether the age of a volatile value is negligible
1854	 */
1855	private function isVolatileValueAgeNegligible( $age ) {
1856		return ( $age < mt_rand( self::RECENT_SET_LOW_MS, self::RECENT_SET_HIGH_MS ) / 1e3 );
1857	}
1858
1859	/**
1860	 * Check whether set() is rate-limited to avoid concurrent I/O spikes
1861	 *
1862	 * This mitigates problems caused by popular keys suddenly becoming unavailable due to
1863	 * unexpected evictions or cache server outages. These cases are not handled by the usual
1864	 * preemptive refresh logic.
1865	 *
1866	 * With a typical scale-out infrastructure, CPU and query load from getWithSetCallback()
1867	 * invocations is distributed among appservers and replica DBs, but cache operations for
1868	 * a given key route to a single cache server (e.g. striped consistent hashing). A set()
1869	 * stampede to a key can saturate the network link to its cache server. The intensity of
1870	 * the problem is proportionate to the value size and access rate. The duration of the
1871	 * problem is proportionate to value regeneration time.
1872	 *
1873	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1874	 * @param string $kClass
1875	 * @param mixed $value The regenerated value
1876	 * @param float $elapsed Seconds spent fetching, validating, and regenerating the value
1877	 * @param bool $hasLock Whether this thread has an exclusive regeneration lock
1878	 * @return bool Whether it is OK to proceed with a key set operation
1879	 */
1880	private function checkAndSetCooloff( $key, $kClass, $value, $elapsed, $hasLock ) {
1881		$valueSisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE, $this->onHostRoute );
1882		list( $estimatedSize ) = $this->cache->setNewPreparedValues( [
1883			$valueSisterKey => $value
1884		] );
1885
1886		if ( !$hasLock ) {
1887			// Suppose that this cache key is very popular (KEY_HIGH_QPS reads/second).
1888			// After eviction, there will be cache misses until it gets regenerated and saved.
1889			// If the time window when the key is missing lasts less than one second, then the
1890			// number of misses will not reach KEY_HIGH_QPS. This window largely corresponds to
1891			// the key regeneration time. Estimate the count/rate of cache misses, e.g.:
1892			//  - 100 QPS, 20ms regeneration => ~2 misses (< 1s)
1893			//  - 100 QPS, 100ms regeneration => ~10 misses (< 1s)
1894			//  - 100 QPS, 3000ms regeneration => ~300 misses (100/s for 3s)
1895			$missesPerSecForHighQPS = ( min( $elapsed, 1 ) * $this->keyHighQps );
1896
1897			// Determine whether there is enough I/O stampede risk to justify throttling set().
1898			// Estimate unthrottled set() overhead, as bps, from miss count/rate and value size,
1899			// comparing it to the per-key uplink bps limit (KEY_HIGH_UPLINK_BPS), e.g.:
1900			//  - 2 misses (< 1s), 10KB value, 1250000 bps limit => 160000 bits (low risk)
1901			//  - 2 misses (< 1s), 100KB value, 1250000 bps limit => 1600000 bits (high risk)
1902			//  - 10 misses (< 1s), 10KB value, 1250000 bps limit => 800000 bits (low risk)
1903			//  - 10 misses (< 1s), 100KB value, 1250000 bps limit => 8000000 bits (high risk)
1904			//  - 300 misses (100/s), 1KB value, 1250000 bps limit => 800000 bps (low risk)
1905			//  - 300 misses (100/s), 10KB value, 1250000 bps limit => 8000000 bps (high risk)
1906			//  - 300 misses (100/s), 100KB value, 1250000 bps limit => 80000000 bps (high risk)
1907			if ( ( $missesPerSecForHighQPS * $estimatedSize ) >= $this->keyHighUplinkBps ) {
1908				$cooloffSisterKey = $this->makeSisterKey( $key, self::TYPE_COOLOFF );
1909				$this->cache->clearLastError();
1910				if (
1911					!$this->cache->add( $cooloffSisterKey, 1, self::COOLOFF_TTL ) &&
1912					// Don't treat failures due to I/O errors as the key being in cooloff
1913					$this->cache->getLastError() === BagOStuff::ERR_NONE
1914				) {
1915					$this->stats->increment( "wanobjectcache.$kClass.cooloff_bounce" );
1916
1917					return false;
1918				}
1919			}
1920		}
1921
1922		// Corresponding metrics for cache writes that actually get sent over the write
1923		$this->stats->timing( "wanobjectcache.$kClass.regen_set_delay", 1e3 * $elapsed );
1924		$this->stats->updateCount( "wanobjectcache.$kClass.regen_set_bytes", $estimatedSize );
1925
1926		return true;
1927	}
1928
1929	/**
1930	 * @param mixed $value
1931	 * @param float|null $curTTL
1932	 * @param array $curInfo
1933	 * @param callable|null $touchedCallback
1934	 * @return array (current time left or null, UNIX timestamp of last purge or null)
1935	 * @note Callable type hints are not used to avoid class-autoloading
1936	 */
1937	private function resolveCTL( $value, $curTTL, $curInfo, $touchedCallback ) {
1938		if ( $touchedCallback === null || $value === false ) {
1939			return [
1940				$curTTL,
1941				max( $curInfo[self::KEY_TOMB_AS_OF], $curInfo[self::KEY_CHECK_AS_OF] )
1942			];
1943		}
1944
1945		$touched = $touchedCallback( $value );
1946		if ( $touched !== null && $touched >= $curInfo[self::KEY_AS_OF] ) {
1947			$curTTL = min( $curTTL, self::TINY_NEGATIVE, $curInfo[self::KEY_AS_OF] - $touched );
1948		}
1949
1950		return [
1951			$curTTL,
1952			max(
1953				$curInfo[self::KEY_TOMB_AS_OF],
1954				$curInfo[self::KEY_CHECK_AS_OF],
1955				$touched
1956			)
1957		];
1958	}
1959
1960	/**
1961	 * @param mixed $value
1962	 * @param float|null $lastPurge
1963	 * @param callable|null $touchedCallback
1964	 * @return float|null UNIX timestamp of last purge or null
1965	 * @note Callable type hints are not used to avoid class-autoloading
1966	 */
1967	private function resolveTouched( $value, $lastPurge, $touchedCallback ) {
1968		return ( $touchedCallback === null || $value === false )
1969			? $lastPurge // nothing to derive the "touched timestamp" from
1970			: max( $touchedCallback( $value ), $lastPurge );
1971	}
1972
1973	/**
1974	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1975	 * @param float $minAsOf Minimum acceptable "as of" timestamp
1976	 * @return array (cached value or false, cache key metadata map)
1977	 */
1978	private function getInterimValue( $key, $minAsOf ) {
1979		$now = $this->getCurrentTime();
1980
1981		if ( $this->useInterimHoldOffCaching ) {
1982			$wrapped = $this->cache->get(
1983				$this->makeSisterKey( $key, self::TYPE_INTERIM )
1984			);
1985
1986			list( $value, $keyInfo ) = $this->unwrap( $wrapped, $now );
1987			if ( $this->isValid( $value, $keyInfo[self::KEY_AS_OF], $minAsOf ) ) {
1988				return [ $value, $keyInfo ];
1989			}
1990		}
1991
1992		return $this->unwrap( false, $now );
1993	}
1994
1995	/**
1996	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
1997	 * @param mixed $value
1998	 * @param int $ttl
1999	 * @param int|null $version Value version number
2000	 * @param float $walltime How long it took to generate the value in seconds
2001	 */
2002	private function setInterimValue( $key, $value, $ttl, $version, $walltime ) {
2003		$ttl = max( self::INTERIM_KEY_TTL, (int)$ttl );
2004
2005		$wrapped = $this->wrap( $value, $ttl, $version, $this->getCurrentTime(), $walltime );
2006		$this->cache->merge(
2007			$this->makeSisterKey( $key, self::TYPE_INTERIM ),
2008			static function () use ( $wrapped ) {
2009				return $wrapped;
2010			},
2011			$ttl,
2012			1
2013		);
2014	}
2015
2016	/**
2017	 * @param mixed $busyValue
2018	 * @return mixed
2019	 */
2020	private function resolveBusyValue( $busyValue ) {
2021		return ( $busyValue instanceof Closure ) ? $busyValue() : $busyValue;
2022	}
2023
2024	/**
2025	 * Method to fetch multiple cache keys at once with regeneration
2026	 *
2027	 * This works the same as getWithSetCallback() except:
2028	 *   - a) The $keys argument must be the result of WANObjectCache::makeMultiKeys()
2029	 *   - b) The $callback argument must be a callback that takes the following arguments:
2030	 *         - $id: ID of the entity to query
2031	 *         - $oldValue: prior cache value or false if none was present
2032	 *         - &$ttl: reference to the TTL to be assigned to the new value (alterable)
2033	 *         - &$setOpts: reference to the new value set() options (alterable)
2034	 *         - $oldAsOf: generation UNIX timestamp of $oldValue or null if not present
2035	 *   - c) The return value is a map of (cache key => value) in the order of $keyedIds
2036	 *
2037	 * @see WANObjectCache::getWithSetCallback()
2038	 * @see WANObjectCache::getMultiWithUnionSetCallback()
2039	 *
2040	 * Example usage:
2041	 * @code
2042	 *     $rows = $cache->getMultiWithSetCallback(
2043	 *         // Map of cache keys to entity IDs
2044	 *         $cache->makeMultiKeys(
2045	 *             $this->fileVersionIds(),
2046	 *             function ( $id ) use ( $cache ) {
2047	 *                 return $cache->makeKey( 'file-version', $id );
2048	 *             }
2049	 *         ),
2050	 *         // Time-to-live (in seconds)
2051	 *         $cache::TTL_DAY,
2052	 *         // Function that derives the new key value
2053	 *         function ( $id, $oldValue, &$ttl, array &$setOpts ) {
2054	 *             $dbr = wfGetDB( DB_REPLICA );
2055	 *             // Account for any snapshot/replica DB lag
2056	 *             $setOpts += Database::getCacheSetOptions( $dbr );
2057	 *
2058	 *             // Load the row for this file
2059	 *             $queryInfo = File::getQueryInfo();
2060	 *             $row = $dbr->selectRow(
2061	 *                 $queryInfo['tables'],
2062	 *                 $queryInfo['fields'],
2063	 *                 [ 'id' => $id ],
2064	 *                 __METHOD__,
2065	 *                 [],
2066	 *                 $queryInfo['joins']
2067	 *             );
2068	 *
2069	 *             return $row ? (array)$row : false;
2070	 *         },
2071	 *         [
2072	 *             // Process cache for 30 seconds
2073	 *             'pcTTL' => 30,
2074	 *             // Use a dedicated 500 item cache (initialized on-the-fly)
2075	 *             'pcGroup' => 'file-versions:500'
2076	 *         ]
2077	 *     );
2078	 *     $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
2079	 * @endcode
2080	 *
2081	 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
2082	 * @param int $ttl Seconds to live for key updates
2083	 * @param callable $callback Callback the yields entity regeneration callbacks
2084	 * @param array $opts Options map
2085	 * @return mixed[] Map of (cache key => value) in the same order as $keyedIds
2086	 * @since 1.28
2087	 */
2088	final public function getMultiWithSetCallback(
2089		ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
2090	) {
2091		// Batch load required keys into the in-process warmup cache
2092		$this->warmupCache = $this->fetchWrappedValuesForWarmupCache(
2093			$this->getNonProcessCachedMultiKeys( $keyedIds, $opts ),
2094			$opts['checkKeys'] ?? []
2095		);
2096		$this->warmupKeyMisses = 0;
2097
2098		// The required callback signature includes $id as the first argument for convenience
2099		// to distinguish different items. To reuse the code in getWithSetCallback(), wrap the
2100		// callback with a proxy callback that has the standard getWithSetCallback() signature.
2101		// This is defined only once per batch to avoid closure creation overhead.
2102		$proxyCb = static function ( $oldValue, &$ttl, &$setOpts, $oldAsOf, $params )
2103			use ( $callback )
2104		{
2105			return $callback( $params['id'], $oldValue, $ttl, $setOpts, $oldAsOf );
2106		};
2107
2108		$values = [];
2109		foreach ( $keyedIds as $key => $id ) { // preserve order
2110			$values[$key] = $this->getWithSetCallback(
2111				$key,
2112				$ttl,
2113				$proxyCb,
2114				$opts,
2115				[ 'id' => $id ]
2116			);
2117		}
2118
2119		$this->warmupCache = [];
2120
2121		return $values;
2122	}
2123
2124	/**
2125	 * Method to fetch/regenerate multiple cache keys at once
2126	 *
2127	 * This works the same as getWithSetCallback() except:
2128	 *   - a) The $keys argument expects the result of WANObjectCache::makeMultiKeys()
2129	 *   - b) The $callback argument expects a callback returning a map of (ID => new value)
2130	 *        for all entity IDs in $ids and it takes the following arguments:
2131	 *          - $ids: list of entity IDs that require cache regeneration
2132	 *          - &$ttls: reference to the (entity ID => new TTL) map (alterable)
2133	 *          - &$setOpts: reference to the new value set() options (alterable)
2134	 *   - c) The return value is a map of (cache key => value) in the order of $keyedIds
2135	 *   - d) The "lockTSE" and "busyValue" options are ignored
2136	 *
2137	 * @see WANObjectCache::getWithSetCallback()
2138	 * @see WANObjectCache::getMultiWithSetCallback()
2139	 *
2140	 * Example usage:
2141	 * @code
2142	 *     $rows = $cache->getMultiWithUnionSetCallback(
2143	 *         // Map of cache keys to entity IDs
2144	 *         $cache->makeMultiKeys(
2145	 *             $this->fileVersionIds(),
2146	 *             function ( $id ) use ( $cache ) {
2147	 *                 return $cache->makeKey( 'file-version', $id );
2148	 *             }
2149	 *         ),
2150	 *         // Time-to-live (in seconds)
2151	 *         $cache::TTL_DAY,
2152	 *         // Function that derives the new key value
2153	 *         function ( array $ids, array &$ttls, array &$setOpts ) {
2154	 *             $dbr = wfGetDB( DB_REPLICA );
2155	 *             // Account for any snapshot/replica DB lag
2156	 *             $setOpts += Database::getCacheSetOptions( $dbr );
2157	 *
2158	 *             // Load the rows for these files
2159	 *             $rows = [];
2160	 *             $queryInfo = File::getQueryInfo();
2161	 *             $res = $dbr->select(
2162	 *                 $queryInfo['tables'],
2163	 *                 $queryInfo['fields'],
2164	 *                 [ 'id' => $ids ],
2165	 *                 __METHOD__,
2166	 *                 [],
2167	 *                 $queryInfo['joins']
2168	 *             );
2169	 *             foreach ( $res as $row ) {
2170	 *                 $rows[$row->id] = $row;
2171	 *                 $mtime = wfTimestamp( TS_UNIX, $row->timestamp );
2172	 *                 $ttls[$row->id] = $this->adaptiveTTL( $mtime, $ttls[$row->id] );
2173	 *             }
2174	 *
2175	 *             return $rows;
2176	 *         },
2177	 *         ]
2178	 *     );
2179	 *     $files = array_map( [ __CLASS__, 'newFromRow' ], $rows );
2180	 * @endcode
2181	 *
2182	 * @param ArrayIterator $keyedIds Result of WANObjectCache::makeMultiKeys()
2183	 * @param int $ttl Seconds to live for key updates
2184	 * @param callable $callback Callback the yields entity regeneration callbacks
2185	 * @param array $opts Options map
2186	 * @return mixed[] Map of (cache key => value) in the same order as $keyedIds
2187	 * @since 1.30
2188	 */
2189	final public function getMultiWithUnionSetCallback(
2190		ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
2191	) {
2192		$checkKeys = $opts['checkKeys'] ?? [];
2193		unset( $opts['lockTSE'] ); // incompatible
2194		unset( $opts['busyValue'] ); // incompatible
2195
2196		// Batch load required keys into the in-process warmup cache
2197		$keysByIdGet = $this->getNonProcessCachedMultiKeys( $keyedIds, $opts );
2198		$this->warmupCache = $this->fetchWrappedValuesForWarmupCache( $keysByIdGet, $checkKeys );
2199		$this->warmupKeyMisses = 0;
2200
2201		// IDs of entities known to be in need of regeneration
2202		$idsRegen = [];
2203
2204		// Find out which keys are missing/deleted/stale
2205		$resByKey = $this->fetchKeys( $keysByIdGet, $checkKeys );
2206		foreach ( $keysByIdGet as $id => $key ) {
2207			$res = $resByKey[$key];
2208			$value = $res[self::RES_VALUE];
2209			$metadata = $res[self::RES_METADATA];
2210			if ( $value === false || $metadata[self::KEY_CUR_TTL] < 0 ) {
2211				$idsRegen[] = $id;
2212			}
2213		}
2214
2215		// Run the callback to populate the regeneration value map for all required IDs
2216		$newSetOpts = [];
2217		$newTTLsById = array_fill_keys( $idsRegen, $ttl );
2218		$newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
2219
2220		// The required callback signature includes $id as the first argument for convenience
2221		// to distinguish different items. To reuse the code in getWithSetCallback(), wrap the
2222		// callback with a proxy callback that has the standard getWithSetCallback() signature.
2223		// This is defined only once per batch to avoid closure creation overhead.
2224		$proxyCb = static function ( $oldValue, &$ttl, &$setOpts, $oldAsOf, $params )
2225			use ( $callback, $newValsById, $newTTLsById, $newSetOpts )
2226		{
2227			$id = $params['id'];
2228
2229			if ( array_key_exists( $id, $newValsById ) ) {
2230				// Value was already regerated as expected, so use the value in $newValsById
2231				$newValue = $newValsById[$id];
2232				$ttl = $newTTLsById[$id];
2233				$setOpts = $newSetOpts;
2234			} else {
2235				// Pre-emptive/popularity refresh and version mismatch cases are not detected
2236				// above and thus $newValsById has no entry. Run $callback on this single entity.
2237				$ttls = [ $id => $ttl ];
2238				$newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
2239				$ttl = $ttls[$id];
2240			}
2241
2242			return $newValue;
2243		};
2244
2245		// Run the cache-aside logic using warmupCache instead of persistent cache queries
2246		$values = [];
2247		foreach ( $keyedIds as $key => $id ) { // preserve order
2248			$values[$key] = $this->getWithSetCallback(
2249				$key,
2250				$ttl,
2251				$proxyCb,
2252				$opts,
2253				[ 'id' => $id ]
2254			);
2255		}
2256
2257		$this->warmupCache = [];
2258
2259		return $values;
2260	}
2261
2262	/**
2263	 * Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp
2264	 *
2265	 * This sets stale keys' time-to-live at HOLDOFF_TTL seconds, which both avoids
2266	 * broadcasting in mcrouter setups and also avoids races with new tombstones.
2267	 *
2268	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
2269	 * @param int $purgeTimestamp UNIX timestamp of purge
2270	 * @param bool &$isStale Whether the key is stale
2271	 * @return bool Success
2272	 * @since 1.28
2273	 */
2274	final public function reap( $key, $purgeTimestamp, &$isStale = false ) {
2275		$valueSisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE );
2276
2277		$minAsOf = $purgeTimestamp + self::HOLDOFF_TTL;
2278		$wrapped = $this->cache->get( $valueSisterKey );
2279		if ( is_array( $wrapped ) && $wrapped[self::FLD_TIME] < $minAsOf ) {
2280			$isStale = true;
2281			$this->logger->warning( "Reaping stale value key '$key'." );
2282			$ttlReap = self::HOLDOFF_TTL; // avoids races with tombstone creation
2283			$ok = $this->cache->changeTTL( $valueSisterKey, $ttlReap );
2284			if ( !$ok ) {
2285				$this->logger->error( "Could not complete reap of key '$key'." );
2286			}
2287
2288			return $ok;
2289		}
2290
2291		$isStale = false;
2292
2293		return true;
2294	}
2295
2296	/**
2297	 * Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp
2298	 *
2299	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
2300	 * @param int $purgeTimestamp UNIX timestamp of purge
2301	 * @param bool &$isStale Whether the key is stale
2302	 * @return bool Success
2303	 * @since 1.28
2304	 */
2305	final public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
2306		$checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
2307
2308		$wrapped = $this->cache->get( $checkSisterKey );
2309		$purge = $this->parsePurgeValue( $wrapped );
2310		if ( $purge && $purge[self::PURGE_TIME] < $purgeTimestamp ) {
2311			$isStale = true;
2312			$this->logger->warning( "Reaping stale check key '$key'." );
2313			$ok = $this->cache->changeTTL( $checkSisterKey, self::TTL_SECOND );
2314			if ( !$ok ) {
2315				$this->logger->error( "Could not complete reap of check key '$key'." );
2316			}
2317
2318			return $ok;
2319		}
2320
2321		$isStale = false;
2322
2323		return false;
2324	}
2325
2326	/**
2327	 * Make a cache key for the global keyspace and given components
2328	 *
2329	 * @see IStoreKeyEncoder::makeGlobalKey()
2330	 *
2331	 * @param string $collection Key collection name component
2332	 * @param string|int ...$components Additional, ordered, key components for entity IDs
2333	 * @return string Colon-separated, keyspace-prepended, ordered list of encoded components
2334	 * @since 1.27
2335	 */
2336	public function makeGlobalKey( $collection, ...$components ) {
2337		return $this->cache->makeGlobalKey( ...func_get_args() );
2338	}
2339
2340	/**
2341	 * Make a cache key using the "global" keyspace for the given components
2342	 *
2343	 * @see IStoreKeyEncoder::makeKey()
2344	 *
2345	 * @param string $collection Key collection name component
2346	 * @param string|int ...$components Additional, ordered, key components for entity IDs
2347	 * @return string Colon-separated, keyspace-prepended, ordered list of encoded components
2348	 * @since 1.27
2349	 */
2350	public function makeKey( $collection, ...$components ) {
2351		return $this->cache->makeKey( ...func_get_args() );
2352	}
2353
2354	/**
2355	 * Hash a possibly long string into a suitable component for makeKey()/makeGlobalKey()
2356	 *
2357	 * @param string $component A raw component used in building a cache key
2358	 * @return string 64 character HMAC using a stable secret for public collision resistance
2359	 * @since 1.34
2360	 */
2361	public function hash256( $component ) {
2362		return hash_hmac( 'sha256', $component, $this->secret );
2363	}
2364
2365	/**
2366	 * Get an iterator of (cache key => entity ID) for a list of entity IDs
2367	 *
2368	 * The callback takes an ID string and returns a key via makeKey()/makeGlobalKey().
2369	 * There should be no network nor filesystem I/O used in the callback. The entity
2370	 * ID/key mapping must be 1:1 or an exception will be thrown. If hashing is needed,
2371	 * then use the hash256() method.
2372	 *
2373	 * Example usage for the default keyspace:
2374	 * @code
2375	 *     $keyedIds = $cache->makeMultiKeys(
2376	 *         $modules,
2377	 *         function ( $module ) use ( $cache ) {
2378	 *             return $cache->makeKey( 'module-info', $module );
2379	 *         }
2380	 *     );
2381	 * @endcode
2382	 *
2383	 * Example usage for mixed default and global keyspace:
2384	 * @code
2385	 *     $keyedIds = $cache->makeMultiKeys(
2386	 *         $filters,
2387	 *         function ( $filter ) use ( $cache ) {
2388	 *             return ( strpos( $filter, 'central:' ) === 0 )
2389	 *                 ? $cache->makeGlobalKey( 'regex-filter', $filter )
2390	 *                 : $cache->makeKey( 'regex-filter', $filter )
2391	 *         }
2392	 *     );
2393	 * @endcode
2394	 *
2395	 * Example usage with hashing:
2396	 * @code
2397	 *     $keyedIds = $cache->makeMultiKeys(
2398	 *         $urls,
2399	 *         function ( $url ) use ( $cache ) {
2400	 *             return $cache->makeKey( 'url-info', $cache->hash256( $url ) );
2401	 *         }
2402	 *     );
2403	 * @endcode
2404	 *
2405	 * @see WANObjectCache::makeKey()
2406	 * @see WANObjectCache::makeGlobalKey()
2407	 * @see WANObjectCache::hash256()
2408	 *
2409	 * @param string[]|int[] $ids List of entity IDs
2410	 * @param callable $keyCallback Function returning makeKey()/makeGlobalKey() on the input ID
2411	 * @return ArrayIterator Iterator of (cache key => ID); order of $ids is preserved
2412	 * @throws UnexpectedValueException
2413	 * @since 1.28
2414	 */
2415	final public function makeMultiKeys( array $ids, $keyCallback ) {
2416		$idByKey = [];
2417		foreach ( $ids as $id ) {
2418			// Discourage triggering of automatic makeKey() hashing in some backends
2419			if ( strlen( $id ) > 64 ) {
2420				$this->logger->warning( __METHOD__ . ": long ID '$id'; use hash256()" );
2421			}
2422			$key = $keyCallback( $id, $this );
2423			// Edge case: ignore key collisions due to duplicate $ids like "42" and 42
2424			if ( !isset( $idByKey[$key] ) ) {
2425				$idByKey[$key] = $id;
2426			} elseif ( (string)$id !== (string)$idByKey[$key] ) {
2427				throw new UnexpectedValueException(
2428					"Cache key collision; IDs ('$id','{$idByKey[$key]}') map to '$key'"
2429				);
2430			}
2431		}
2432
2433		return new ArrayIterator( $idByKey );
2434	}
2435
2436	/**
2437	 * Get an (ID => value) map from (i) a non-unique list of entity IDs, and (ii) the list
2438	 * of corresponding entity values by first appearance of each ID in the entity ID list
2439	 *
2440	 * For use with getMultiWithSetCallback() and getMultiWithUnionSetCallback().
2441	 *
2442	 * *Only* use this method if the entity ID/key mapping is trivially 1:1 without exception.
2443	 * Key generation method must utitilize the *full* entity ID in the key (not a hash of it).
2444	 *
2445	 * Example usage:
2446	 * @code
2447	 *     $poems = $cache->getMultiWithSetCallback(
2448	 *         $cache->makeMultiKeys(
2449	 *             $uuids,
2450	 *             function ( $uuid ) use ( $cache ) {
2451	 *                 return $cache->makeKey( 'poem', $uuid );
2452	 *             }
2453	 *         ),
2454	 *         $cache::TTL_DAY,
2455	 *         function ( $uuid ) use ( $url ) {
2456	 *             return $this->http->run( [ 'method' => 'GET', 'url' => "$url/$uuid" ] );
2457	 *         }
2458	 *     );
2459	 *     $poemsByUUID = $cache->multiRemap( $uuids, $poems );
2460	 * @endcode
2461	 *
2462	 * @see WANObjectCache::makeMultiKeys()
2463	 * @see WANObjectCache::getMultiWithSetCallback()
2464	 * @see WANObjectCache::getMultiWithUnionSetCallback()
2465	 *
2466	 * @param string[]|int[] $ids Entity ID list makeMultiKeys()
2467	 * @param mixed[] $res Result of getMultiWithSetCallback()/getMultiWithUnionSetCallback()
2468	 * @return mixed[] Map of (ID => value); order of $ids is preserved
2469	 * @since 1.34
2470	 */
2471	final public function multiRemap( array $ids, array $res ) {
2472		if ( count( $ids ) !== count( $res ) ) {
2473			// If makeMultiKeys() is called on a list of non-unique IDs, then the resulting
2474			// ArrayIterator will have less entries due to "first appearance" de-duplication
2475			$ids = array_keys( array_flip( $ids ) );
2476			if ( count( $ids ) !== count( $res ) ) {
2477				throw new UnexpectedValueException( "Multi-key result does not match ID list" );
2478			}
2479		}
2480
2481		return array_combine( $ids, $res );
2482	}
2483
2484	/**
2485	 * Get the "last error" registered; clearLastError() should be called manually
2486	 * @return int ERR_* class constant for the "last error" registry
2487	 */
2488	final public function getLastError() {
2489		$code = $this->cache->getLastError();
2490		switch ( $code ) {
2491			case BagOStuff::ERR_NONE:
2492				return self::ERR_NONE;
2493			case BagOStuff::ERR_NO_RESPONSE:
2494				return self::ERR_NO_RESPONSE;
2495			case BagOStuff::ERR_UNREACHABLE:
2496				return self::ERR_UNREACHABLE;
2497			default:
2498				return self::ERR_UNEXPECTED;
2499		}
2500	}
2501
2502	/**
2503	 * Clear the "last error" registry
2504	 */
2505	final public function clearLastError() {
2506		$this->cache->clearLastError();
2507	}
2508
2509	/**
2510	 * Clear the in-process caches; useful for testing
2511	 *
2512	 * @since 1.27
2513	 */
2514	public function clearProcessCache() {
2515		$this->processCaches = [];
2516	}
2517
2518	/**
2519	 * Enable or disable the use of brief caching for tombstoned keys
2520	 *
2521	 * When a key is purged via delete(), there normally is a period where caching
2522	 * is hold-off limited to an extremely short time. This method will disable that
2523	 * caching, forcing the callback to run for any of:
2524	 *   - WANObjectCache::getWithSetCallback()
2525	 *   - WANObjectCache::getMultiWithSetCallback()
2526	 *   - WANObjectCache::getMultiWithUnionSetCallback()
2527	 *
2528	 * This is useful when both:
2529	 *   - a) the database used by the callback is known to be up-to-date enough
2530	 *        for some particular purpose (e.g. replica DB has applied transaction X)
2531	 *   - b) the caller needs to exploit that fact, and therefore needs to avoid the
2532	 *        use of inherently volatile and possibly stale interim keys
2533	 *
2534	 * @see WANObjectCache::delete()
2535	 * @param bool $enabled Whether to enable interim caching
2536	 * @since 1.31
2537	 */
2538	final public function useInterimHoldOffCaching( $enabled ) {
2539		$this->useInterimHoldOffCaching = $enabled;
2540	}
2541
2542	/**
2543	 * @param int $flag ATTR_* class constant
2544	 * @return int QOS_* class constant
2545	 * @since 1.28
2546	 */
2547	public function getQoS( $flag ) {
2548		return $this->cache->getQoS( $flag );
2549	}
2550
2551	/**
2552	 * Get a TTL that is higher for objects that have not changed recently
2553	 *
2554	 * This is useful for keys that get explicit purges and DB or purge relay
2555	 * lag is a potential concern (especially how it interacts with CDN cache)
2556	 *
2557	 * Example usage:
2558	 * @code
2559	 *     // Last-modified time of page
2560	 *     $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
2561	 *     // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
2562	 *     // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
2563	 *     // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
2564	 *     $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
2565	 * @endcode
2566	 *
2567	 * Another use case is when there are no applicable "last modified" fields in the DB,
2568	 * and there are too many dependencies for explicit purges to be viable, and the rate of
2569	 * change to relevant content is unstable, and it is highly valued to have the cached value
2570	 * be as up-to-date as possible.
2571	 *
2572	 * Example usage:
2573	 * @code
2574	 *     $query = "<some complex query>";
2575	 *     $idListFromComplexQuery = $cache->getWithSetCallback(
2576	 *         $cache->makeKey( 'complex-graph-query', $hashOfQuery ),
2577	 *         GraphQueryClass::STARTING_TTL,
2578	 *         function ( $oldValue, &$ttl, array &$setOpts, $oldAsOf ) use ( $query, $cache ) {
2579	 *             $gdb = $this->getReplicaGraphDbConnection();
2580	 *             // Account for any snapshot/replica DB lag
2581	 *             $setOpts += GraphDatabase::getCacheSetOptions( $gdb );
2582	 *
2583	 *             $newList = iterator_to_array( $gdb->query( $query ) );
2584	 *             sort( $newList, SORT_NUMERIC ); // normalize
2585	 *
2586	 *             $minTTL = GraphQueryClass::MIN_TTL;
2587	 *             $maxTTL = GraphQueryClass::MAX_TTL;
2588	 *             if ( $oldValue !== false ) {
2589	 *                 // Note that $oldAsOf is the last time this callback ran
2590	 *                 $ttl = ( $newList === $oldValue )
2591	 *                     // No change: cache for 150% of the age of $oldValue
2592	 *                     ? $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, 1.5 )
2593	 *                     // Changed: cache for 50% of the age of $oldValue
2594	 *                     : $cache->adaptiveTTL( $oldAsOf, $maxTTL, $minTTL, .5 );
2595	 *             }
2596	 *
2597	 *             return $newList;
2598	 *        },
2599	 *        [
2600	 *             // Keep stale values around for doing comparisons for TTL calculations.
2601	 *             // High values improve long-tail keys hit-rates, though might waste space.
2602	 *             'staleTTL' => GraphQueryClass::GRACE_TTL
2603	 *        ]
2604	 *     );
2605	 * @endcode
2606	 *
2607	 * @param int|float $mtime UNIX timestamp
2608	 * @param int $maxTTL Maximum TTL (seconds)
2609	 * @param int $minTTL Minimum TTL (seconds); Default: 30
2610	 * @param float $factor Value in the range (0,1); Default: .2
2611	 * @return int Adaptive TTL
2612	 * @since 1.28
2613	 */
2614	public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
2615		if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
2616			$mtime = (int)$mtime; // handle fractional seconds and string integers
2617		}
2618
2619		if ( !is_int( $mtime ) || $mtime <= 0 ) {
2620			return $minTTL; // no last-modified time provided
2621		}
2622
2623		$age = $this->getCurrentTime() - $mtime;
2624
2625		return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
2626	}
2627
2628	/**
2629	 * @return int Number of warmup key cache misses last round
2630	 * @since 1.30
2631	 */
2632	final public function getWarmupKeyMisses() {
2633		return $this->warmupKeyMisses;
2634	}
2635
2636	/**
2637	 * Set a sister key to a purge value in all datacenters
2638	 *
2639	 * This method should not wait for the operation to complete on remote datacenters
2640	 *
2641	 * Since older purge values can sometimes arrive after newer ones, use a relative expiry
2642	 * so that even if the older value replaces the newer value, the TTL will greater than the
2643	 * remaining TTL on the older value (assuming that all purges for a key use the same TTL).
2644	 *
2645	 * @param array<string,string> $purgeBySisterKey Map of
2646	 *  (sister key => result of makeTombstonePurgeValue()/makeCheckKeyPurgeValue())
2647	 * @param int $ttl Seconds to keep the purge value around
2648	 * @return bool Success
2649	 */
2650	protected function relayVolatilePurges( array $purgeBySisterKey, int $ttl ) {
2651		$purgeByRouteKey = [];
2652		foreach ( $purgeBySisterKey as $sisterKey => $purge ) {
2653			if ( $this->broadcastRoute !== null ) {
2654				$routeKey = $this->prependRoute( $sisterKey, $this->broadcastRoute );
2655			} else {
2656				$routeKey = $sisterKey;
2657			}
2658			$purgeByRouteKey[$routeKey] = $purge;
2659		}
2660
2661		if ( count( $purgeByRouteKey ) == 1 ) {
2662			$purge = reset( $purgeByRouteKey );
2663			$ok = $this->cache->set( key( $purgeByRouteKey ), $purge, $ttl );
2664		} else {
2665			$ok = $this->cache->setMulti( $purgeByRouteKey, $ttl );
2666		}
2667
2668		return $ok;
2669	}
2670
2671	/**
2672	 * Remove a sister key from all datacenters
2673	 *
2674	 * This method should not wait for the operation to complete on remote datacenters
2675	 *
2676	 * @param string $sisterKey A value, "check", or flux sister key
2677	 * @return bool Success
2678	 */
2679	protected function relayNonVolatilePurge( string $sisterKey ) {
2680		if ( $this->broadcastRoute !== null ) {
2681			$routeKey = $this->prependRoute( $sisterKey, $this->broadcastRoute );
2682		} else {
2683			$routeKey = $sisterKey;
2684		}
2685
2686		return $this->cache->delete( $routeKey );
2687	}
2688
2689	/**
2690	 * @param string $sisterKey Sister key
2691	 * @param string $route Key routing prefix
2692	 * @return string
2693	 */
2694	protected function prependRoute( string $sisterKey, string $route ) {
2695		if ( $sisterKey[0] === '/' ) {
2696			throw new RuntimeException( "Sister key '$sisterKey' already contains a route." );
2697		}
2698
2699		return $route . $sisterKey;
2700	}
2701
2702	/**
2703	 * Schedule a deferred cache regeneration if possible
2704	 *
2705	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
2706	 * @param int $ttl Seconds to live
2707	 * @param callable $callback
2708	 * @param array $opts
2709	 * @param array $cbParams
2710	 * @return bool Success
2711	 * @note Callable type hints are not used to avoid class-autoloading
2712	 */
2713	private function scheduleAsyncRefresh( $key, $ttl, $callback, array $opts, array $cbParams ) {
2714		if ( !$this->asyncHandler ) {
2715			return false;
2716		}
2717		// Update the cache value later, such during post-send of an HTTP request. This forces
2718		// cache regeneration by setting "minAsOf" to infinity, meaning that no existing value
2719		// is considered valid. Furthermore, note that preemptive regeneration is not applicable
2720		// to invalid values, so there is no risk of infinite preemptive regeneration loops.
2721		$func = $this->asyncHandler;
2722		$func( function () use ( $key, $ttl, $callback, $opts, $cbParams ) {
2723			$opts['minAsOf'] = INF;
2724			try {
2725				$this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams );
2726			} catch ( Exception $e ) {
2727				// Log some context for easier debugging
2728				$this->logger->error( 'Async refresh failed for {key}', [
2729					'key' => $key,
2730					'ttl' => $ttl,
2731					'exception' => $e
2732				] );
2733				throw $e;
2734			}
2735		} );
2736
2737		return true;
2738	}
2739
2740	/**
2741	 * Check if a key is fresh or in the grace window and thus due for randomized reuse
2742	 *
2743	 * If $curTTL > 0 (e.g. value not expired) then this returns true. If $curTTL <= -$graceTTL
2744	 * (e.g. value out of grace) then this returns false. Otherwise, the chance of this
2745	 * returning true decreases steadily from 100% to 0% as the |$curTTL| moves from 0 to
2746	 * $graceTTL seconds.
2747	 *
2748	 * This approach handles widely varying levels of cache access traffic.
2749	 *
2750	 * @param float $curTTL Approximate TTL left on the key
2751	 * @param int $graceTTL Consider using stale values if $curTTL is greater than this
2752	 * @return bool
2753	 */
2754	private function isAliveOrInGracePeriod( $curTTL, $graceTTL ) {
2755		if ( $curTTL > 0 ) {
2756			return true;
2757		} elseif ( $graceTTL <= 0 ) {
2758			return false;
2759		}
2760
2761		$ageStale = abs( $curTTL ); // seconds of staleness
2762		$curGraceTTL = ( $graceTTL - $ageStale ); // current grace-time-to-live
2763		if ( $curGraceTTL <= 0 ) {
2764			return false; // already out of grace period
2765		}
2766
2767		// Chance of using a stale value is the complement of the chance of refreshing it
2768		return !$this->worthRefreshExpiring( $curGraceTTL, $graceTTL, $graceTTL );
2769	}
2770
2771	/**
2772	 * Check if a key is nearing expiration and thus due for randomized regeneration
2773	 *
2774	 * If $curTTL is greater than the "low" threshold (e.g. not nearing expiration) then this
2775	 * returns false. If $curTTL <= 0 (e.g. value already expired), then this returns false.
2776	 * Otherwise, the chance of this returning true increases steadily from 0% to 100% as
2777	 * $curTTL moves from the "low" threshold down to 0 seconds.
2778	 *
2779	 * This approach handles widely varying levels of cache access traffic.
2780	 *
2781	 * The logical TTL will be used as the "low" threshold if it is less than $lowTTL.
2782	 *
2783	 * @param float $curTTL Approximate TTL left on the key
2784	 * @param float $logicalTTL Full logical TTL assigned to the key
2785	 * @param float $lowTTL Consider a refresh when $curTTL is less than this; the "low" threshold
2786	 * @return bool
2787	 */
2788	protected function worthRefreshExpiring( $curTTL, $logicalTTL, $lowTTL ) {
2789		if ( $lowTTL <= 0 ) {
2790			return false;
2791		}
2792
2793		// T264787: avoid having keys start off with a high chance of being refreshed;
2794		// the point where refreshing becomes possible cannot precede the key lifetime.
2795		$effectiveLowTTL = min( $lowTTL, $logicalTTL ?: INF );
2796
2797		if ( $curTTL >= $effectiveLowTTL || $curTTL <= 0 ) {
2798			return false;
2799		}
2800
2801		$chance = ( 1 - $curTTL / $effectiveLowTTL );
2802
2803		// @phan-suppress-next-line PhanTypeMismatchArgumentInternal
2804		$decision = ( mt_rand( 1, 1e9 ) <= 1e9 * $chance );
2805
2806		$this->logger->debug(
2807			"worthRefreshExpiring($curTTL, $logicalTTL, $lowTTL): " .
2808			"p = $chance; refresh = " . ( $decision ? 'Y' : 'N' )
2809		);
2810
2811		return $decision;
2812	}
2813
2814	/**
2815	 * Check if a key is due for randomized regeneration due to its popularity
2816	 *
2817	 * This is used so that popular keys can preemptively refresh themselves for higher
2818	 * consistency (especially in the case of purge loss/delay). Unpopular keys can remain
2819	 * in cache with their high nominal TTL. This means popular keys keep good consistency,
2820	 * whether the data changes frequently or not, and long-tail keys get to stay in cache
2821	 * and get hits too. Similar to worthRefreshExpiring(), randomization is used.
2822	 *
2823	 * @param float $asOf UNIX timestamp of the value
2824	 * @param int $ageNew Age of key when this might recommend refreshing (seconds)
2825	 * @param int $timeTillRefresh Age of key when it should be refreshed if popular (seconds)
2826	 * @param float $now The current UNIX timestamp
2827	 * @return bool
2828	 */
2829	protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
2830		if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
2831			return false;
2832		}
2833
2834		$age = $now - $asOf;
2835		$timeOld = $age - $ageNew;
2836		if ( $timeOld <= 0 ) {
2837			return false;
2838		}
2839
2840		$popularHitsPerSec = 1;
2841		// Lifecycle is: new, ramp-up refresh chance, full refresh chance.
2842		// Note that the "expected # of refreshes" for the ramp-up time range is half
2843		// of what it would be if P(refresh) was at its full value during that time range.
2844		$refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
2845		// P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
2846		// P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1 (by definition)
2847		// P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
2848		$chance = 1 / ( $popularHitsPerSec * $refreshWindowSec );
2849		// Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
2850		$chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
2851
2852		// @phan-suppress-next-line PhanTypeMismatchArgumentInternal
2853		$decision = ( mt_rand( 1, 1e9 ) <= 1e9 * $chance );
2854
2855		$this->logger->debug(
2856			"worthRefreshPopular($asOf, $ageNew, $timeTillRefresh, $now): " .
2857			"p = $chance; refresh = " . ( $decision ? 'Y' : 'N' )
2858		);
2859
2860		return $decision;
2861	}
2862
2863	/**
2864	 * Check if $value is not false, versioned (if needed), and not older than $minTime (if set)
2865	 *
2866	 * @param array|bool $value
2867	 * @param float $asOf The time $value was generated
2868	 * @param float $minAsOf Minimum acceptable "as of" timestamp
2869	 * @param float|null $purgeTime The last time the value was invalidated
2870	 * @return bool
2871	 */
2872	protected function isValid( $value, $asOf, $minAsOf, $purgeTime = null ) {
2873		// Avoid reading any key not generated after the latest delete() or touch
2874		$safeMinAsOf = max( $minAsOf, $purgeTime + self::TINY_POSTIVE );
2875
2876		if ( $value === false ) {
2877			return false;
2878		} elseif ( $safeMinAsOf > 0 && $asOf < $minAsOf ) {
2879			return false;
2880		}
2881
2882		return true;
2883	}
2884
2885	/**
2886	 * @param mixed $value
2887	 * @param int $ttl Seconds to live or zero for "indefinite"
2888	 * @param int|null $version Value version number or null if not versioned
2889	 * @param float $now Unix Current timestamp just before calling set()
2890	 * @param float|null $walltime How long it took to generate the value in seconds
2891	 * @return array
2892	 */
2893	private function wrap( $value, $ttl, $version, $now, $walltime ) {
2894		// Returns keys in ascending integer order for PHP7 array packing:
2895		// https://nikic.github.io/2014/12/22/PHPs-new-hashtable-implementation.html
2896		$wrapped = [
2897			self::FLD_FORMAT_VERSION => self::VERSION,
2898			self::FLD_VALUE => $value,
2899			self::FLD_TTL => $ttl,
2900			self::FLD_TIME => $now
2901		];
2902		if ( $version !== null ) {
2903			$wrapped[self::FLD_VALUE_VERSION] = $version;
2904		}
2905		if ( $walltime >= self::GENERATION_SLOW_SEC ) {
2906			$wrapped[self::FLD_GENERATION_TIME] = $walltime;
2907		}
2908
2909		return $wrapped;
2910	}
2911
2912	/**
2913	 * @param array|string|false $wrapped The entry at a cache key (false if key is nonexistant)
2914	 * @param float $now Unix Current timestamp (preferrably pre-query)
2915	 * @return array<mixed,array> (value or false if absent/tombstoned/malformed, metadata map).
2916	 * The cache key metadata map includes the following metadata:
2917	 *   - WANObjectCache::KEY_VERSION: value version number; null if there is no value
2918	 *   - WANObjectCache::KEY_AS_OF: value generation timestamp (UNIX); null if there is no value
2919	 *   - WANObjectCache::KEY_TTL: assigned logical TTL (seconds); null if there is no value
2920	 *   - WANObjectCache::KEY_CUR_TTL: remaining logical TTL (seconds) (negative if tombstoned)
2921	 *   - WANObjectCache::KEY_TOMB_AS_OF: tombstone timestamp (UNIX); null if not tombstoned
2922	 * @phan-return array{0:mixed,1:array{version:?mixed,asOf:?mixed,ttl:?int|float,curTTL:?int|float,tombAsOf:?mixed}}
2923	 */
2924	private function unwrap( $wrapped, $now ) {
2925		$value = false;
2926		$info = $this->newKeyInfoPlaceholder();
2927
2928		if ( is_array( $wrapped ) ) {
2929			// Entry expected to be a cached value; validate it
2930			if (
2931				( $wrapped[self::FLD_FORMAT_VERSION] ?? null ) === self::VERSION &&
2932				$wrapped[self::FLD_TIME] >= $this->epoch
2933			) {
2934				if ( $wrapped[self::FLD_TTL] > 0 ) {
2935					// Get the approximate time left on the key
2936					$age = $now - $wrapped[self::FLD_TIME];
2937					$curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
2938				} else {
2939					// Key had no TTL, so the time left is unbounded
2940					$curTTL = INF;
2941				}
2942				$value = $wrapped[self::FLD_VALUE];
2943				$info[self::KEY_VERSION] = $wrapped[self::FLD_VALUE_VERSION] ?? null;
2944				$info[self::KEY_AS_OF] = $wrapped[self::FLD_TIME];
2945				$info[self::KEY_CUR_TTL] = $curTTL;
2946				$info[self::KEY_TTL] = $wrapped[self::FLD_TTL];
2947			}
2948		} else {
2949			// Entry expected to be a tombstone; parse it
2950			$purge = $this->parsePurgeValue( $wrapped );
2951			if ( $purge !== false ) {
2952				// Tombstoned keys should always have a negative current $ttl
2953				$info[self::KEY_CUR_TTL] =
2954					min( $purge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
2955				$info[self::KEY_TOMB_AS_OF] = $purge[self::PURGE_TIME];
2956			}
2957		}
2958
2959		return [ $value, $info ];
2960	}
2961
2962	/**
2963	 * @return null[]
2964	 */
2965	private function newKeyInfoPlaceholder() {
2966		return [
2967			self::KEY_VERSION => null,
2968			self::KEY_AS_OF => null,
2969			self::KEY_TTL => null,
2970			self::KEY_CUR_TTL => null,
2971			self::KEY_TOMB_AS_OF => null
2972		];
2973	}
2974
2975	/**
2976	 * @param string $key String of the format <scope>:<collection>[:<constant or variable>]...
2977	 * @return string A collection name to describe this class of key
2978	 */
2979	private function determineKeyClassForStats( $key ) {
2980		$parts = explode( ':', $key, 3 );
2981		// Sanity fallback in case the key was not made by makeKey.
2982		// Replace dots because they are special in StatsD (T232907)
2983		return strtr( $parts[1] ?? $parts[0], '.', '_' );
2984	}
2985
2986	/**
2987	 * Extract purge metadata from cached value if it is a valid purge value
2988	 *
2989	 * Valid purge values come from makeTombstonePurgeValue()/makeCheckKeyPurgeValue()
2990	 *
2991	 * @param mixed $value Cached value
2992	 * @return array|bool Array containing a UNIX timestamp (float) and hold-off period (integer),
2993	 *  or false if value isn't a valid purge value
2994	 */
2995	private function parsePurgeValue( $value ) {
2996		if ( !is_string( $value ) ) {
2997			return false;
2998		}
2999
3000		$segments = explode( ':', $value, 3 );
3001		if ( isset( $segments[2] ) ) {
3002			$prefix = $segments[0];
3003			$timestamp = (float)$segments[1];
3004			$holdoff = (int)$segments[2];
3005		} elseif ( isset( $segments[1] ) ) {
3006			$prefix = $segments[0];
3007			$timestamp = (float)$segments[1];
3008			// Value tombstones don't store hold-off TTLs
3009			$holdoff = self::HOLDOFF_TTL;
3010		} else {
3011			return false;
3012		}
3013
3014		if ( "{$prefix}:" !== self::PURGE_VAL_PREFIX || $timestamp < $this->epoch ) {
3015			// Not a purge value or the purge value is too old
3016			return false;
3017		}
3018
3019		return [ self::PURGE_TIME => $timestamp, self::PURGE_HOLDOFF => $holdoff ];
3020	}
3021
3022	/**
3023	 * @param float $timestamp UNIX timestamp
3024	 * @return string Wrapped purge value; format is "PURGED:<timestamp>"
3025	 */
3026	private function makeTombstonePurgeValue( $timestamp ) {
3027		return self::PURGE_VAL_PREFIX . number_format( $timestamp, 4, '.', '' );
3028	}
3029
3030	/**
3031	 * @param float $timestamp UNIX timestamp
3032	 * @param int $holdoff In seconds
3033	 * @return string Wrapped purge value; format is "PURGED:<timestamp>:<holdoff>"
3034	 */
3035	private function makeCheckPurgeValue( $timestamp, int $holdoff ) {
3036		return self::PURGE_VAL_PREFIX . number_format( $timestamp, 4, '.', '' ) . ":$holdoff";
3037	}
3038
3039	/**
3040	 * @param string $group
3041	 * @return MapCacheLRU
3042	 */
3043	private function getProcessCache( $group ) {
3044		if ( !isset( $this->processCaches[$group] ) ) {
3045			list( , $size ) = explode( ':', $group );
3046			$this->processCaches[$group] = new MapCacheLRU( (int)$size );
3047			if ( $this->wallClockOverride !== null ) {
3048				$this->processCaches[$group]->setMockTime( $this->wallClockOverride );
3049			}
3050		}
3051
3052		return $this->processCaches[$group];
3053	}
3054
3055	/**
3056	 * @param string $key Cache key made with makeKey()/makeGlobalKey()
3057	 * @param int $version
3058	 * @return string
3059	 */
3060	private function getProcessCacheKey( $key, $version ) {
3061		return $key . ' ' . (int)$version;
3062	}
3063
3064	/**
3065	 * @param ArrayIterator $keys
3066	 * @param array $opts
3067	 * @return string[] Map of (ID => cache key)
3068	 */
3069	private function getNonProcessCachedMultiKeys( ArrayIterator $keys, array $opts ) {
3070		$pcTTL = $opts['pcTTL'] ?? self::TTL_UNCACHEABLE;
3071
3072		$keysMissing = [];
3073		if ( $pcTTL > 0 && $this->callbackDepth == 0 ) {
3074			$version = $opts['version'] ?? null;
3075			$pCache = $this->getProcessCache( $opts['pcGroup'] ?? self::PC_PRIMARY );
3076			foreach ( $keys as $key => $id ) {
3077				if ( !$pCache->has( $this->getProcessCacheKey( $key, $version ), $pcTTL ) ) {
3078					$keysMissing[$id] = $key;
3079				}
3080			}
3081		}
3082
3083		return $keysMissing;
3084	}
3085
3086	/**
3087	 * @param string[] $keys Cache keys made with makeKey()/makeGlobalKey()
3088	 * @param string[]|string[][] $checkKeys Map of (integer or cache key => "check" key(s));
3089	 *  "check" keys must also be made with makeKey()/makeGlobalKey()
3090	 * @return array<string,mixed> Map of (sister key => value, or, false if not found)
3091	 */
3092	private function fetchWrappedValuesForWarmupCache( array $keys, array $checkKeys ) {
3093		if ( !$keys ) {
3094			return [];
3095		}
3096
3097		// Get all the value keys to fetch...
3098		$sisterKeys = $this->makeSisterKeys( $keys, self::TYPE_VALUE, $this->onHostRoute );
3099		// Get all the flux keys to fetch...
3100		if ( $this->onHostRoute !== null ) {
3101			foreach ( $keys as $key ) {
3102				$sisterKeys[] = $this->makeSisterKey( $key, self::TYPE_FLUX );
3103			}
3104		}
3105		// Get all the "check" keys to fetch...
3106		foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) {
3107			// Note: avoid array_merge() inside loop in case there are many keys
3108			if ( is_int( $i ) ) {
3109				// Single "check" key that applies to all value keys
3110				$sisterKeys[] = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP );
3111			} else {
3112				// List of "check" keys that apply to a specific value key
3113				foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) {
3114					$sisterKeys[] = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP );
3115				}
3116			}
3117		}
3118
3119		$wrappedBySisterKey = $this->cache->getMulti( $sisterKeys );
3120		$wrappedBySisterKey += array_fill_keys( $sisterKeys, false );
3121
3122		return $wrappedBySisterKey;
3123	}
3124
3125	/**
3126	 * @return float UNIX timestamp
3127	 * @codeCoverageIgnore
3128	 */
3129	protected function getCurrentTime() {
3130		if ( $this->wallClockOverride ) {
3131			return $this->wallClockOverride;
3132		}
3133
3134		$clockTime = (float)time(); // call this first
3135		// microtime() uses an initial gettimeofday() call added to usage clocks.
3136		// This can severely drift from time() and the microtime() value of other threads
3137		// due to undercounting of the amount of time elapsed. Instead of seeing the current
3138		// time as being in the past, use the value of time(). This avoids setting cache values
3139		// that will immediately be seen as expired and possibly cause stampedes.
3140		return max( microtime( true ), $clockTime );
3141	}
3142
3143	/**
3144	 * @param float|null &$time Mock UNIX timestamp for testing
3145	 * @codeCoverageIgnore
3146	 */
3147	public function setMockTime( &$time ) {
3148		$this->wallClockOverride =& $time;
3149		$this->cache->setMockTime( $time );
3150		foreach ( $this->processCaches as $pCache ) {
3151			$pCache->setMockTime( $time );
3152		}
3153	}
3154}
3155