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