Debian Codegraph @

includes/libs/objectcache/WANObjectCache.php

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