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