Merge "Add API warnings when upload is same as older versions"
[lhc/web/wiklou.git] / includes / libs / objectcache / WANObjectCache.php
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 * @author Aaron Schulz
21 */
22
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26
27 /**
28 * Multi-datacenter aware caching interface
29 *
30 * All operations go to the local datacenter cache, except for delete(),
31 * touchCheckKey(), and resetCheckKey(), which broadcast to all datacenters.
32 *
33 * This class is intended for caching data from primary stores.
34 * If the get() method does not return a value, then the caller
35 * should query the new value and backfill the cache using set().
36 * The preferred way to do this logic is through getWithSetCallback().
37 * When querying the store on cache miss, the closest DB replica
38 * should be used. Try to avoid heavyweight DB master or quorum reads.
39 * When the source data changes, a purge method should be called.
40 * Since purges are expensive, they should be avoided. One can do so if:
41 * - a) The object cached is immutable; or
42 * - b) Validity is checked against the source after get(); or
43 * - c) Using a modest TTL is reasonably correct and performant
44 *
45 * The simplest purge method is delete().
46 *
47 * There are two supported ways to handle broadcasted operations:
48 * - a) Configure the 'purge' EventRelayer to point to a valid PubSub endpoint
49 * that has subscribed listeners on the cache servers applying the cache updates.
50 * - b) Ignore the 'purge' EventRelayer configuration (default is NullEventRelayer)
51 * and set up mcrouter as the underlying cache backend, using one of the memcached
52 * BagOStuff classes as 'cache'. Use OperationSelectorRoute in the mcrouter settings
53 * to configure 'set' and 'delete' operations to go to all DCs via AllAsyncRoute and
54 * configure other operations to go to the local DC via PoolRoute (for reference,
55 * see https://github.com/facebook/mcrouter/wiki/List-of-Route-Handles).
56 *
57 * Broadcasted operations like delete() and touchCheckKey() are done asynchronously
58 * in all datacenters this way, though the local one should likely be near immediate.
59 *
60 * This means that callers in all datacenters may see older values for however many
61 * milliseconds that the purge took to reach that datacenter. As with any cache, this
62 * should not be relied on for cases where reads are used to determine writes to source
63 * (e.g. non-cache) data stores, except when reading immutable data.
64 *
65 * All values are wrapped in metadata arrays. Keys use a "WANCache:" prefix
66 * to avoid collisions with keys that are not wrapped as metadata arrays. The
67 * prefixes are as follows:
68 * - a) "WANCache:v" : used for regular value keys
69 * - b) "WANCache:i" : used for temporarily storing values of tombstoned keys
70 * - c) "WANCache:t" : used for storing timestamp "check" keys
71 * - d) "WANCache:m" : used for temporary mutex keys to avoid cache stampedes
72 *
73 * @ingroup Cache
74 * @since 1.26
75 */
76 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
77 /** @var BagOStuff The local datacenter cache */
78 protected $cache;
79 /** @var HashBagOStuff Script instance PHP cache */
80 protected $procCache;
81 /** @var string Purge channel name */
82 protected $purgeChannel;
83 /** @var EventRelayer Bus that handles purge broadcasts */
84 protected $purgeRelayer;
85 /** @var LoggerInterface */
86 protected $logger;
87
88 /** @var int ERR_* constant for the "last error" registry */
89 protected $lastRelayError = self::ERR_NONE;
90
91 /** Max time expected to pass between delete() and DB commit finishing */
92 const MAX_COMMIT_DELAY = 3;
93 /** Max replication+snapshot lag before applying TTL_LAGGED or disallowing set() */
94 const MAX_READ_LAG = 7;
95 /** Seconds to tombstone keys on delete() */
96 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
97
98 /** Seconds to keep dependency purge keys around */
99 const CHECK_KEY_TTL = self::TTL_YEAR;
100 /** Seconds to keep lock keys around */
101 const LOCK_TTL = 10;
102 /** Default remaining TTL at which to consider pre-emptive regeneration */
103 const LOW_TTL = 30;
104 /** Default time-since-expiry on a miss that makes a key "hot" */
105 const LOCK_TSE = 1;
106
107 /** Idiom for getWithSetCallback() callbacks to avoid calling set() */
108 const TTL_UNCACHEABLE = -1;
109 /** Idiom for getWithSetCallback() callbacks to 'lockTSE' logic */
110 const TSE_NONE = -1;
111 /** Max TTL to store keys when a data sourced is lagged */
112 const TTL_LAGGED = 30;
113 /** Idiom for delete() for "no hold-off" */
114 const HOLDOFF_NONE = 0;
115
116 /** Tiny negative float to use when CTL comes up >= 0 due to clock skew */
117 const TINY_NEGATIVE = -0.000001;
118
119 /** Cache format version number */
120 const VERSION = 1;
121
122 const FLD_VERSION = 0; // key to cache version number
123 const FLD_VALUE = 1; // key to the cached value
124 const FLD_TTL = 2; // key to the original TTL
125 const FLD_TIME = 3; // key to the cache time
126 const FLD_FLAGS = 4; // key to the flags bitfield
127 const FLD_HOLDOFF = 5; // key to any hold-off TTL
128
129 /** @var integer Treat this value as expired-on-arrival */
130 const FLG_STALE = 1;
131
132 const ERR_NONE = 0; // no error
133 const ERR_NO_RESPONSE = 1; // no response
134 const ERR_UNREACHABLE = 2; // can't connect
135 const ERR_UNEXPECTED = 3; // response gave some error
136 const ERR_RELAY = 4; // relay broadcast failed
137
138 const VALUE_KEY_PREFIX = 'WANCache:v:';
139 const INTERIM_KEY_PREFIX = 'WANCache:i:';
140 const TIME_KEY_PREFIX = 'WANCache:t:';
141 const MUTEX_KEY_PREFIX = 'WANCache:m:';
142
143 const PURGE_VAL_PREFIX = 'PURGED:';
144
145 const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
146 const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
147
148 const MAX_PC_KEYS = 1000; // max keys to keep in process cache
149
150 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
151
152 /**
153 * @param array $params
154 * - cache : BagOStuff object for a persistent cache
155 * - channels : Map of (action => channel string). Actions include "purge".
156 * - relayers : Map of (action => EventRelayer object). Actions include "purge".
157 * - logger : LoggerInterface object
158 */
159 public function __construct( array $params ) {
160 $this->cache = $params['cache'];
161 $this->procCache = new HashBagOStuff( [ 'maxKeys' => self::MAX_PC_KEYS ] );
162 $this->purgeChannel = isset( $params['channels']['purge'] )
163 ? $params['channels']['purge']
164 : self::DEFAULT_PURGE_CHANNEL;
165 $this->purgeRelayer = isset( $params['relayers']['purge'] )
166 ? $params['relayers']['purge']
167 : new EventRelayerNull( [] );
168 $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
169 }
170
171 public function setLogger( LoggerInterface $logger ) {
172 $this->logger = $logger;
173 }
174
175 /**
176 * Get an instance that wraps EmptyBagOStuff
177 *
178 * @return WANObjectCache
179 */
180 public static function newEmpty() {
181 return new self( [
182 'cache' => new EmptyBagOStuff(),
183 'pool' => 'empty',
184 'relayer' => new EventRelayerNull( [] )
185 ] );
186 }
187
188 /**
189 * Fetch the value of a key from cache
190 *
191 * If supplied, $curTTL is set to the remaining TTL (current time left):
192 * - a) INF; if $key exists, has no TTL, and is not expired by $checkKeys
193 * - b) float (>=0); if $key exists, has a TTL, and is not expired by $checkKeys
194 * - c) float (<0); if $key is tombstoned, stale, or existing but expired by $checkKeys
195 * - d) null; if $key does not exist and is not tombstoned
196 *
197 * If a key is tombstoned, $curTTL will reflect the time since delete().
198 *
199 * The timestamp of $key will be checked against the last-purge timestamp
200 * of each of $checkKeys. Those $checkKeys not in cache will have the last-purge
201 * initialized to the current timestamp. If any of $checkKeys have a timestamp
202 * greater than that of $key, then $curTTL will reflect how long ago $key
203 * became invalid. Callers can use $curTTL to know when the value is stale.
204 * The $checkKeys parameter allow mass invalidations by updating a single key:
205 * - a) Each "check" key represents "last purged" of some source data
206 * - b) Callers pass in relevant "check" keys as $checkKeys in get()
207 * - c) When the source data that "check" keys represent changes,
208 * the touchCheckKey() method is called on them
209 *
210 * Source data entities might exists in a DB that uses snapshot isolation
211 * (e.g. the default REPEATABLE-READ in innoDB). Even for mutable data, that
212 * isolation can largely be maintained by doing the following:
213 * - a) Calling delete() on entity change *and* creation, before DB commit
214 * - b) Keeping transaction duration shorter than delete() hold-off TTL
215 *
216 * However, pre-snapshot values might still be seen if an update was made
217 * in a remote datacenter but the purge from delete() didn't relay yet.
218 *
219 * Consider using getWithSetCallback() instead of get() and set() cycles.
220 * That method has cache slam avoiding features for hot/expensive keys.
221 *
222 * @param string $key Cache key
223 * @param mixed $curTTL Approximate TTL left on the key if present/tombstoned [returned]
224 * @param array $checkKeys List of "check" keys
225 * @param float &$asOf UNIX timestamp of cached value; null on failure [returned]
226 * @return mixed Value of cache key or false on failure
227 */
228 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
229 $curTTLs = [];
230 $asOfs = [];
231 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
232 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
233 $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null;
234
235 return isset( $values[$key] ) ? $values[$key] : false;
236 }
237
238 /**
239 * Fetch the value of several keys from cache
240 *
241 * @see WANObjectCache::get()
242 *
243 * @param array $keys List of cache keys
244 * @param array $curTTLs Map of (key => approximate TTL left) for existing keys [returned]
245 * @param array $checkKeys List of check keys to apply to all $keys. May also apply "check"
246 * keys to specific cache keys only by using cache keys as keys in the $checkKeys array.
247 * @param float[] &$asOfs Map of (key => UNIX timestamp of cached value; null on failure)
248 * @return array Map of (key => value) for keys that exist
249 */
250 final public function getMulti(
251 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
252 ) {
253 $result = [];
254 $curTTLs = [];
255 $asOfs = [];
256
257 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
258 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
259
260 $checkKeysForAll = [];
261 $checkKeysByKey = [];
262 $checkKeysFlat = [];
263 foreach ( $checkKeys as $i => $keys ) {
264 $prefixed = self::prefixCacheKeys( (array)$keys, self::TIME_KEY_PREFIX );
265 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
266 // Is this check keys for a specific cache key, or for all keys being fetched?
267 if ( is_int( $i ) ) {
268 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
269 } else {
270 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
271 ? array_merge( $checkKeysByKey[$i], $prefixed )
272 : $prefixed;
273 }
274 }
275
276 // Fetch all of the raw values
277 $wrappedValues = $this->cache->getMulti( array_merge( $valueKeys, $checkKeysFlat ) );
278 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
279 $now = microtime( true );
280
281 // Collect timestamps from all "check" keys
282 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
283 $purgeValuesByKey = [];
284 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
285 $purgeValuesByKey[$cacheKey] =
286 $this->processCheckKeys( $checks, $wrappedValues, $now );
287 }
288
289 // Get the main cache value for each key and validate them
290 foreach ( $valueKeys as $vKey ) {
291 if ( !isset( $wrappedValues[$vKey] ) ) {
292 continue; // not found
293 }
294
295 $key = substr( $vKey, $vPrefixLen ); // unprefix
296
297 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
298 if ( $value !== false ) {
299 $result[$key] = $value;
300
301 // Force dependant keys to be invalid for a while after purging
302 // to reduce race conditions involving stale data getting cached
303 $purgeValues = $purgeValuesForAll;
304 if ( isset( $purgeValuesByKey[$key] ) ) {
305 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
306 }
307 foreach ( $purgeValues as $purge ) {
308 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
309 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
310 // How long ago this value was expired by *this* check key
311 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
312 // How long ago this value was expired by *any* known check key
313 $curTTL = min( $curTTL, $ago );
314 }
315 }
316 }
317 $curTTLs[$key] = $curTTL;
318 $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
319 }
320
321 return $result;
322 }
323
324 /**
325 * @since 1.27
326 * @param array $timeKeys List of prefixed time check keys
327 * @param array $wrappedValues
328 * @param float $now
329 * @return array List of purge value arrays
330 */
331 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
332 $purgeValues = [];
333 foreach ( $timeKeys as $timeKey ) {
334 $purge = isset( $wrappedValues[$timeKey] )
335 ? self::parsePurgeValue( $wrappedValues[$timeKey] )
336 : false;
337 if ( $purge === false ) {
338 // Key is not set or invalid; regenerate
339 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
340 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
341 $purge = self::parsePurgeValue( $newVal );
342 }
343 $purgeValues[] = $purge;
344 }
345 return $purgeValues;
346 }
347
348 /**
349 * Set the value of a key in cache
350 *
351 * Simply calling this method when source data changes is not valid because
352 * the changes do not replicate to the other WAN sites. In that case, delete()
353 * should be used instead. This method is intended for use on cache misses.
354 *
355 * If the data was read from a snapshot-isolated transactions (e.g. the default
356 * REPEATABLE-READ in innoDB), use 'since' to avoid the following race condition:
357 * - a) T1 starts
358 * - b) T2 updates a row, calls delete(), and commits
359 * - c) The HOLDOFF_TTL passes, expiring the delete() tombstone
360 * - d) T1 reads the row and calls set() due to a cache miss
361 * - e) Stale value is stuck in cache
362 *
363 * Setting 'lag' and 'since' help avoids keys getting stuck in stale states.
364 *
365 * Example usage:
366 * @code
367 * $dbr = wfGetDB( DB_REPLICA );
368 * $setOpts = Database::getCacheSetOptions( $dbr );
369 * // Fetch the row from the DB
370 * $row = $dbr->selectRow( ... );
371 * $key = $cache->makeKey( 'building', $buildingId );
372 * $cache->set( $key, $row, $cache::TTL_DAY, $setOpts );
373 * @endcode
374 *
375 * @param string $key Cache key
376 * @param mixed $value
377 * @param integer $ttl Seconds to live. Special values are:
378 * - WANObjectCache::TTL_INDEFINITE: Cache forever
379 * @param array $opts Options map:
380 * - lag : Seconds of replica DB lag. Typically, this is either the replica DB lag
381 * before the data was read or, if applicable, the replica DB lag before
382 * the snapshot-isolated transaction the data was read from started.
383 * Default: 0 seconds
384 * - since : UNIX timestamp of the data in $value. Typically, this is either
385 * the current time the data was read or (if applicable) the time when
386 * the snapshot-isolated transaction the data was read from started.
387 * Default: 0 seconds
388 * - pending : Whether this data is possibly from an uncommitted write transaction.
389 * Generally, other threads should not see values from the future and
390 * they certainly should not see ones that ended up getting rolled back.
391 * Default: false
392 * - lockTSE : if excessive replication/snapshot lag is detected, then store the value
393 * with this TTL and flag it as stale. This is only useful if the reads for
394 * this key use getWithSetCallback() with "lockTSE" set.
395 * Default: WANObjectCache::TSE_NONE
396 * @return bool Success
397 */
398 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
399 $now = microtime( true );
400 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
401 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
402 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
403
404 // Do not cache potentially uncommitted data as it might get rolled back
405 if ( !empty( $opts['pending'] ) ) {
406 $this->logger->info( "Rejected set() for $key due to pending writes." );
407
408 return true; // no-op the write for being unsafe
409 }
410
411 $wrapExtra = []; // additional wrapped value fields
412 // Check if there's a risk of writing stale data after the purge tombstone expired
413 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
414 // Case A: read lag with "lockTSE"; save but record value as stale
415 if ( $lockTSE >= 0 ) {
416 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
417 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
418 // Case B: any long-running transaction; ignore this set()
419 } elseif ( $age > self::MAX_READ_LAG ) {
420 $this->logger->warning( "Rejected set() for $key due to snapshot lag." );
421
422 return true; // no-op the write for being unsafe
423 // Case C: high replication lag; lower TTL instead of ignoring all set()s
424 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
425 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
426 $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
427 // Case D: medium length request with medium replication lag; ignore this set()
428 } else {
429 $this->logger->warning( "Rejected set() for $key due to high read lag." );
430
431 return true; // no-op the write for being unsafe
432 }
433 }
434
435 // Wrap that value with time/TTL/version metadata
436 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
437
438 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
439 return ( is_string( $cWrapped ) )
440 ? false // key is tombstoned; do nothing
441 : $wrapped;
442 };
443
444 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl, 1 );
445 }
446
447 /**
448 * Purge a key from all datacenters
449 *
450 * This should only be called when the underlying data (being cached)
451 * changes in a significant way. This deletes the key and starts a hold-off
452 * period where the key cannot be written to for a few seconds (HOLDOFF_TTL).
453 * This is done to avoid the following race condition:
454 * - a) Some DB data changes and delete() is called on a corresponding key
455 * - b) A request refills the key with a stale value from a lagged DB
456 * - c) The stale value is stuck there until the key is expired/evicted
457 *
458 * This is implemented by storing a special "tombstone" value at the cache
459 * key that this class recognizes; get() calls will return false for the key
460 * and any set() calls will refuse to replace tombstone values at the key.
461 * For this to always avoid stale value writes, the following must hold:
462 * - a) Replication lag is bounded to being less than HOLDOFF_TTL; or
463 * - b) If lag is higher, the DB will have gone into read-only mode already
464 *
465 * Note that set() can also be lag-aware and lower the TTL if it's high.
466 *
467 * When using potentially long-running ACID transactions, a good pattern is
468 * to use a pre-commit hook to issue the delete. This means that immediately
469 * after commit, callers will see the tombstone in cache upon purge relay.
470 * It also avoids the following race condition:
471 * - a) T1 begins, changes a row, and calls delete()
472 * - b) The HOLDOFF_TTL passes, expiring the delete() tombstone
473 * - c) T2 starts, reads the row and calls set() due to a cache miss
474 * - d) T1 finally commits
475 * - e) Stale value is stuck in cache
476 *
477 * Example usage:
478 * @code
479 * $dbw->startAtomic( __METHOD__ ); // start of request
480 * ... <execute some stuff> ...
481 * // Update the row in the DB
482 * $dbw->update( ... );
483 * $key = $cache->makeKey( 'homes', $homeId );
484 * // Purge the corresponding cache entry just before committing
485 * $dbw->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
486 * $cache->delete( $key );
487 * } );
488 * ... <execute some stuff> ...
489 * $dbw->endAtomic( __METHOD__ ); // end of request
490 * @endcode
491 *
492 * The $ttl parameter can be used when purging values that have not actually changed
493 * recently. For example, a cleanup script to purge cache entries does not really need
494 * a hold-off period, so it can use HOLDOFF_NONE. Likewise for user-requested purge.
495 * Note that $ttl limits the effective range of 'lockTSE' for getWithSetCallback().
496 *
497 * If called twice on the same key, then the last hold-off TTL takes precedence. For
498 * idempotence, the $ttl should not vary for different delete() calls on the same key.
499 *
500 * @param string $key Cache key
501 * @param integer $ttl Tombstone TTL; Default: WANObjectCache::HOLDOFF_TTL
502 * @return bool True if the item was purged or not found, false on failure
503 */
504 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
505 $key = self::VALUE_KEY_PREFIX . $key;
506
507 if ( $ttl <= 0 ) {
508 // Publish the purge to all datacenters
509 $ok = $this->relayDelete( $key );
510 } else {
511 // Publish the purge to all datacenters
512 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE );
513 }
514
515 return $ok;
516 }
517
518 /**
519 * Fetch the value of a timestamp "check" key
520 *
521 * The key will be *initialized* to the current time if not set,
522 * so only call this method if this behavior is actually desired
523 *
524 * The timestamp can be used to check whether a cached value is valid.
525 * Callers should not assume that this returns the same timestamp in
526 * all datacenters due to relay delays.
527 *
528 * The level of staleness can roughly be estimated from this key, but
529 * if the key was evicted from cache, such calculations may show the
530 * time since expiry as ~0 seconds.
531 *
532 * Note that "check" keys won't collide with other regular keys.
533 *
534 * @param string $key
535 * @return float UNIX timestamp of the check key
536 */
537 final public function getCheckKeyTime( $key ) {
538 $key = self::TIME_KEY_PREFIX . $key;
539
540 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
541 if ( $purge !== false ) {
542 $time = $purge[self::FLD_TIME];
543 } else {
544 // Casting assures identical floats for the next getCheckKeyTime() calls
545 $now = (string)microtime( true );
546 $this->cache->add( $key,
547 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
548 self::CHECK_KEY_TTL
549 );
550 $time = (float)$now;
551 }
552
553 return $time;
554 }
555
556 /**
557 * Purge a "check" key from all datacenters, invalidating keys that use it
558 *
559 * This should only be called when the underlying data (being cached)
560 * changes in a significant way, and it is impractical to call delete()
561 * on all keys that should be changed. When get() is called on those
562 * keys, the relevant "check" keys must be supplied for this to work.
563 *
564 * The "check" key essentially represents a last-modified field.
565 * When touched, the field will be updated on all cache servers.
566 * Keys using it via get(), getMulti(), or getWithSetCallback() will
567 * be invalidated. It is treated as being HOLDOFF_TTL seconds in the future
568 * by those methods to avoid race conditions where dependent keys get updated
569 * with stale values (e.g. from a DB replica DB).
570 *
571 * This is typically useful for keys with hardcoded names or in some cases
572 * dynamically generated names where a low number of combinations exist.
573 * When a few important keys get a large number of hits, a high cache
574 * time is usually desired as well as "lockTSE" logic. The resetCheckKey()
575 * method is less appropriate in such cases since the "time since expiry"
576 * cannot be inferred, causing any get() after the reset to treat the key
577 * as being "hot", resulting in more stale value usage.
578 *
579 * Note that "check" keys won't collide with other regular keys.
580 *
581 * @see WANObjectCache::get()
582 * @see WANObjectCache::getWithSetCallback()
583 * @see WANObjectCache::resetCheckKey()
584 *
585 * @param string $key Cache key
586 * @param int $holdoff HOLDOFF_TTL or HOLDOFF_NONE constant
587 * @return bool True if the item was purged or not found, false on failure
588 */
589 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
590 // Publish the purge to all datacenters
591 return $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
592 }
593
594 /**
595 * Delete a "check" key from all datacenters, invalidating keys that use it
596 *
597 * This is similar to touchCheckKey() in that keys using it via get(), getMulti(),
598 * or getWithSetCallback() will be invalidated. The differences are:
599 * - a) The "check" key will be deleted from all caches and lazily
600 * re-initialized when accessed (rather than set everywhere)
601 * - b) Thus, dependent keys will be known to be invalid, but not
602 * for how long (they are treated as "just" purged), which
603 * effects any lockTSE logic in getWithSetCallback()
604 * - c) Since "check" keys are initialized only on the server the key hashes
605 * to, any temporary ejection of that server will cause the value to be
606 * seen as purged as a new server will initialize the "check" key.
607 *
608 * The advantage is that this does not place high TTL keys on every cache
609 * server, making it better for code that will cache many different keys
610 * and either does not use lockTSE or uses a low enough TTL anyway.
611 *
612 * This is typically useful for keys with dynamically generated names
613 * where a high number of combinations exist.
614 *
615 * Note that "check" keys won't collide with other regular keys.
616 *
617 * @see WANObjectCache::get()
618 * @see WANObjectCache::getWithSetCallback()
619 * @see WANObjectCache::touchCheckKey()
620 *
621 * @param string $key Cache key
622 * @return bool True if the item was purged or not found, false on failure
623 */
624 final public function resetCheckKey( $key ) {
625 // Publish the purge to all datacenters
626 return $this->relayDelete( self::TIME_KEY_PREFIX . $key );
627 }
628
629 /**
630 * Method to fetch/regenerate cache keys
631 *
632 * On cache miss, the key will be set to the callback result via set()
633 * (unless the callback returns false) and that result will be returned.
634 * The arguments supplied to the callback are:
635 * - $oldValue : current cache value or false if not present
636 * - &$ttl : a reference to the TTL which can be altered
637 * - &$setOpts : a reference to options for set() which can be altered
638 *
639 * It is strongly recommended to set the 'lag' and 'since' fields to avoid race conditions
640 * that can cause stale values to get stuck at keys. Usually, callbacks ignore the current
641 * value, but it can be used to maintain "most recent X" values that come from time or
642 * sequence based source data, provided that the "as of" id/time is tracked. Note that
643 * preemptive regeneration and $checkKeys can result in a non-false current value.
644 *
645 * Usage of $checkKeys is similar to get() and getMulti(). However, rather than the caller
646 * having to inspect a "current time left" variable (e.g. $curTTL, $curTTLs), a cache
647 * regeneration will automatically be triggered using the callback.
648 *
649 * The simplest way to avoid stampedes for hot keys is to use
650 * the 'lockTSE' option in $opts. If cache purges are needed, also:
651 * - a) Pass $key into $checkKeys
652 * - b) Use touchCheckKey( $key ) instead of delete( $key )
653 *
654 * Example usage (typical key):
655 * @code
656 * $catInfo = $cache->getWithSetCallback(
657 * // Key to store the cached value under
658 * $cache->makeKey( 'cat-attributes', $catId ),
659 * // Time-to-live (in seconds)
660 * $cache::TTL_MINUTE,
661 * // Function that derives the new key value
662 * function ( $oldValue, &$ttl, array &$setOpts ) {
663 * $dbr = wfGetDB( DB_REPLICA );
664 * // Account for any snapshot/replica DB lag
665 * $setOpts += Database::getCacheSetOptions( $dbr );
666 *
667 * return $dbr->selectRow( ... );
668 * }
669 * );
670 * @endcode
671 *
672 * Example usage (key that is expensive and hot):
673 * @code
674 * $catConfig = $cache->getWithSetCallback(
675 * // Key to store the cached value under
676 * $cache->makeKey( 'site-cat-config' ),
677 * // Time-to-live (in seconds)
678 * $cache::TTL_DAY,
679 * // Function that derives the new key value
680 * function ( $oldValue, &$ttl, array &$setOpts ) {
681 * $dbr = wfGetDB( DB_REPLICA );
682 * // Account for any snapshot/replica DB lag
683 * $setOpts += Database::getCacheSetOptions( $dbr );
684 *
685 * return CatConfig::newFromRow( $dbr->selectRow( ... ) );
686 * },
687 * [
688 * // Calling touchCheckKey() on this key invalidates the cache
689 * 'checkKeys' => [ $cache->makeKey( 'site-cat-config' ) ],
690 * // Try to only let one datacenter thread manage cache updates at a time
691 * 'lockTSE' => 30,
692 * // Avoid querying cache servers multiple times in a web request
693 * 'pcTTL' => $cache::TTL_PROC_LONG
694 * ]
695 * );
696 * @endcode
697 *
698 * Example usage (key with dynamic dependencies):
699 * @code
700 * $catState = $cache->getWithSetCallback(
701 * // Key to store the cached value under
702 * $cache->makeKey( 'cat-state', $cat->getId() ),
703 * // Time-to-live (seconds)
704 * $cache::TTL_HOUR,
705 * // Function that derives the new key value
706 * function ( $oldValue, &$ttl, array &$setOpts ) {
707 * // Determine new value from the DB
708 * $dbr = wfGetDB( DB_REPLICA );
709 * // Account for any snapshot/replica DB lag
710 * $setOpts += Database::getCacheSetOptions( $dbr );
711 *
712 * return CatState::newFromResults( $dbr->select( ... ) );
713 * },
714 * [
715 * // The "check" keys that represent things the value depends on;
716 * // Calling touchCheckKey() on any of them invalidates the cache
717 * 'checkKeys' => [
718 * $cache->makeKey( 'sustenance-bowls', $cat->getRoomId() ),
719 * $cache->makeKey( 'people-present', $cat->getHouseId() ),
720 * $cache->makeKey( 'cat-laws', $cat->getCityId() ),
721 * ]
722 * ]
723 * );
724 * @endcode
725 *
726 * Example usage (hot key holding most recent 100 events):
727 * @code
728 * $lastCatActions = $cache->getWithSetCallback(
729 * // Key to store the cached value under
730 * $cache->makeKey( 'cat-last-actions', 100 ),
731 * // Time-to-live (in seconds)
732 * 10,
733 * // Function that derives the new key value
734 * function ( $oldValue, &$ttl, array &$setOpts ) {
735 * $dbr = wfGetDB( DB_REPLICA );
736 * // Account for any snapshot/replica DB lag
737 * $setOpts += Database::getCacheSetOptions( $dbr );
738 *
739 * // Start off with the last cached list
740 * $list = $oldValue ?: [];
741 * // Fetch the last 100 relevant rows in descending order;
742 * // only fetch rows newer than $list[0] to reduce scanning
743 * $rows = iterator_to_array( $dbr->select( ... ) );
744 * // Merge them and get the new "last 100" rows
745 * return array_slice( array_merge( $new, $list ), 0, 100 );
746 * },
747 * [
748 * // Try to only let one datacenter thread manage cache updates at a time
749 * 'lockTSE' => 30,
750 * // Use a magic value when no cache value is ready rather than stampeding
751 * 'busyValue' => 'computing'
752 * ]
753 * );
754 * @endcode
755 *
756 * @see WANObjectCache::get()
757 * @see WANObjectCache::set()
758 *
759 * @param string $key Cache key
760 * @param integer $ttl Seconds to live for key updates. Special values are:
761 * - WANObjectCache::TTL_INDEFINITE: Cache forever
762 * - WANObjectCache::TTL_UNCACHEABLE: Do not cache at all
763 * @param callable $callback Value generation function
764 * @param array $opts Options map:
765 * - checkKeys: List of "check" keys. The key at $key will be seen as invalid when either
766 * touchCheckKey() or resetCheckKey() is called on any of these keys.
767 * Default: [].
768 * - lowTTL: Consider pre-emptive updates when the current TTL (seconds) of the key is less
769 * than this. It becomes more likely over time, becoming certain once the key is expired.
770 * Default: WANObjectCache::LOW_TTL.
771 * - lockTSE: If the key is tombstoned or expired (by checkKeys) less than this many seconds
772 * ago, then try to have a single thread handle cache regeneration at any given time.
773 * Other threads will try to use stale values if possible. If, on miss, the time since
774 * expiration is low, the assumption is that the key is hot and that a stampede is worth
775 * avoiding. Setting this above WANObjectCache::HOLDOFF_TTL makes no difference. The
776 * higher this is set, the higher the worst-case staleness can be.
777 * Use WANObjectCache::TSE_NONE to disable this logic.
778 * Default: WANObjectCache::TSE_NONE.
779 * - busyValue: If no value exists and another thread is currently regenerating it, use this
780 * as a fallback value (or a callback to generate such a value). This assures that cache
781 * stampedes cannot happen if the value falls out of cache. This can be used as insurance
782 * against cache regeneration becoming very slow for some reason (greater than the TTL).
783 * Default: null.
784 * - pcTTL: Process cache the value in this PHP instance for this many seconds. This avoids
785 * network I/O when a key is read several times. This will not cache when the callback
786 * returns false, however. Note that any purges will not be seen while process cached;
787 * since the callback should use replica DBs and they may be lagged or have snapshot
788 * isolation anyway, this should not typically matter.
789 * Default: WANObjectCache::TTL_UNCACHEABLE.
790 * - version: Integer version number. This allows for callers to make breaking changes to
791 * how values are stored while maintaining compatability and correct cache purges. New
792 * versions are stored alongside older versions concurrently. Avoid storing class objects
793 * however, as this reduces compatibility (due to serialization).
794 * Default: null.
795 * @return mixed Value found or written to the key
796 * @note Callable type hints are not used to avoid class-autoloading
797 */
798 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
799 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
800
801 // Try the process cache if enabled
802 $value = ( $pcTTL >= 0 ) ? $this->procCache->get( $key ) : false;
803
804 if ( $value === false ) {
805 unset( $opts['minTime'] ); // not a public feature
806
807 // Fetch the value over the network
808 if ( isset( $opts['version'] ) ) {
809 $version = $opts['version'];
810 $asOf = null;
811 $cur = $this->doGetWithSetCallback(
812 $key,
813 $ttl,
814 function ( $oldValue, &$ttl, &$setOpts ) use ( $callback, $version ) {
815 if ( is_array( $oldValue )
816 && array_key_exists( self::VFLD_DATA, $oldValue )
817 ) {
818 $oldData = $oldValue[self::VFLD_DATA];
819 } else {
820 // VFLD_DATA is not set if an old, unversioned, key is present
821 $oldData = false;
822 }
823
824 return [
825 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts ),
826 self::VFLD_VERSION => $version
827 ];
828 },
829 $opts,
830 $asOf
831 );
832 if ( $cur[self::VFLD_VERSION] === $version ) {
833 // Value created or existed before with version; use it
834 $value = $cur[self::VFLD_DATA];
835 } else {
836 // Value existed before with a different version; use variant key.
837 // Reflect purges to $key by requiring that this key value be newer.
838 $value = $this->doGetWithSetCallback(
839 'cache-variant:' . md5( $key ) . ":$version",
840 $ttl,
841 $callback,
842 // Regenerate value if not newer than $key
843 [ 'version' => null, 'minTime' => $asOf ] + $opts
844 );
845 }
846 } else {
847 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
848 }
849
850 // Update the process cache if enabled
851 if ( $pcTTL >= 0 && $value !== false ) {
852 $this->procCache->set( $key, $value, $pcTTL );
853 }
854 }
855
856 return $value;
857 }
858
859 /**
860 * Do the actual I/O for getWithSetCallback() when needed
861 *
862 * @see WANObjectCache::getWithSetCallback()
863 *
864 * @param string $key
865 * @param integer $ttl
866 * @param callback $callback
867 * @param array $opts Options map for getWithSetCallback() which also includes:
868 * - minTime: Treat values older than this UNIX timestamp as not existing. Default: null.
869 * @param float &$asOf Cache generation timestamp of returned value [returned]
870 * @return mixed
871 * @note Callable type hints are not used to avoid class-autoloading
872 */
873 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
874 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
875 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
876 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
877 $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
878 $minTime = isset( $opts['minTime'] ) ? $opts['minTime'] : 0.0;
879 $versioned = isset( $opts['version'] );
880
881 // Get the current key value
882 $curTTL = null;
883 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
884 $value = $cValue; // return value
885
886 // Determine if a regeneration is desired
887 if ( $value !== false
888 && $curTTL > 0
889 && $this->isValid( $value, $versioned, $asOf, $minTime )
890 && !$this->worthRefresh( $curTTL, $lowTTL )
891 ) {
892 return $value;
893 }
894
895 // A deleted key with a negative TTL left must be tombstoned
896 $isTombstone = ( $curTTL !== null && $value === false );
897 // Assume a key is hot if requested soon after invalidation
898 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
899 // Use the mutex if there is no value and a busy fallback is given
900 $checkBusy = ( $busyValue !== null && $value === false );
901 // Decide whether a single thread should handle regenerations.
902 // This avoids stampedes when $checkKeys are bumped and when preemptive
903 // renegerations take too long. It also reduces regenerations while $key
904 // is tombstoned. This balances cache freshness with avoiding DB load.
905 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
906
907 $lockAcquired = false;
908 if ( $useMutex ) {
909 // Acquire a datacenter-local non-blocking lock
910 if ( $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
911 // Lock acquired; this thread should update the key
912 $lockAcquired = true;
913 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
914 // If it cannot be acquired; then the stale value can be used
915 return $value;
916 } else {
917 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
918 // For hot keys, either another thread has the lock or the lock failed;
919 // use the INTERIM value from the last thread that regenerated it.
920 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
921 list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
922 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
923 $asOf = $wrapped[self::FLD_TIME];
924
925 return $value;
926 }
927 // Use the busy fallback value if nothing else
928 if ( $busyValue !== null ) {
929 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
930 }
931 }
932 }
933
934 if ( !is_callable( $callback ) ) {
935 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
936 }
937
938 // Generate the new value from the callback...
939 $setOpts = [];
940 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts ] );
941 $asOf = microtime( true );
942 // When delete() is called, writes are write-holed by the tombstone,
943 // so use a special INTERIM key to pass the new value around threads.
944 if ( ( $isTombstone && $lockTSE > 0 ) && $value !== false && $ttl >= 0 ) {
945 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
946 $wrapped = $this->wrap( $value, $tempTTL, $asOf );
947 // Avoid using set() to avoid pointless mcrouter broadcasting
948 $this->cache->merge(
949 self::INTERIM_KEY_PREFIX . $key,
950 function () use ( $wrapped ) {
951 return $wrapped;
952 },
953 $tempTTL,
954 1
955 );
956 }
957
958 if ( $value !== false && $ttl >= 0 ) {
959 // Update the cache; this will fail if the key is tombstoned
960 $setOpts['lockTSE'] = $lockTSE;
961 $this->set( $key, $value, $ttl, $setOpts );
962 }
963
964 if ( $lockAcquired ) {
965 // Avoid using delete() to avoid pointless mcrouter broadcasting
966 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, 1 );
967 }
968
969 return $value;
970 }
971
972 /**
973 * @see BagOStuff::makeKey()
974 * @param string ... Key component
975 * @return string
976 * @since 1.27
977 */
978 public function makeKey() {
979 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
980 }
981
982 /**
983 * @see BagOStuff::makeGlobalKey()
984 * @param string ... Key component
985 * @return string
986 * @since 1.27
987 */
988 public function makeGlobalKey() {
989 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
990 }
991
992 /**
993 * Get the "last error" registered; clearLastError() should be called manually
994 * @return int ERR_* class constant for the "last error" registry
995 */
996 final public function getLastError() {
997 if ( $this->lastRelayError ) {
998 // If the cache and the relayer failed, focus on the later.
999 // An update not making it to the relayer means it won't show up
1000 // in other DCs (nor will consistent re-hashing see up-to-date values).
1001 // On the other hand, if just the cache update failed, then it should
1002 // eventually be applied by the relayer.
1003 return $this->lastRelayError;
1004 }
1005
1006 $code = $this->cache->getLastError();
1007 switch ( $code ) {
1008 case BagOStuff::ERR_NONE:
1009 return self::ERR_NONE;
1010 case BagOStuff::ERR_NO_RESPONSE:
1011 return self::ERR_NO_RESPONSE;
1012 case BagOStuff::ERR_UNREACHABLE:
1013 return self::ERR_UNREACHABLE;
1014 default:
1015 return self::ERR_UNEXPECTED;
1016 }
1017 }
1018
1019 /**
1020 * Clear the "last error" registry
1021 */
1022 final public function clearLastError() {
1023 $this->cache->clearLastError();
1024 $this->lastRelayError = self::ERR_NONE;
1025 }
1026
1027 /**
1028 * Clear the in-process caches; useful for testing
1029 *
1030 * @since 1.27
1031 */
1032 public function clearProcessCache() {
1033 $this->procCache->clear();
1034 }
1035
1036 /**
1037 * @param integer $flag ATTR_* class constant
1038 * @return integer QOS_* class constant
1039 * @since 1.28
1040 */
1041 public function getQoS( $flag ) {
1042 return $this->cache->getQoS( $flag );
1043 }
1044
1045 /**
1046 * Get a TTL that is higher for objects that have not changed recently
1047 *
1048 * This is useful for keys that get explicit purges and DB or purge relay
1049 * lag is a potential concern (especially how it interacts with CDN cache)
1050 *
1051 * Example usage:
1052 * @code
1053 * // Last-modified time of page
1054 * $mtime = wfTimestamp( TS_UNIX, $page->getTimestamp() );
1055 * // Get adjusted TTL. If $mtime is 3600 seconds ago and $minTTL/$factor left at
1056 * // defaults, then $ttl is 3600 * .2 = 720. If $minTTL was greater than 720, then
1057 * // $ttl would be $minTTL. If $maxTTL was smaller than 720, $ttl would be $maxTTL.
1058 * $ttl = $cache->adaptiveTTL( $mtime, $cache::TTL_DAY );
1059 * @endcode
1060 *
1061 * @param integer|float $mtime UNIX timestamp
1062 * @param integer $maxTTL Maximum TTL (seconds)
1063 * @param integer $minTTL Minimum TTL (seconds); Default: 30
1064 * @param float $factor Value in the range (0,1); Default: .2
1065 * @return integer Adaptive TTL
1066 * @since 1.28
1067 */
1068 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = .2 ) {
1069 if ( is_float( $mtime ) ) {
1070 $mtime = (int)$mtime; // ignore fractional seconds
1071 }
1072
1073 if ( !is_int( $mtime ) || $mtime <= 0 ) {
1074 return $minTTL; // no last-modified time provided
1075 }
1076
1077 $age = time() - $mtime;
1078
1079 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1080 }
1081
1082 /**
1083 * Do the actual async bus purge of a key
1084 *
1085 * This must set the key to "PURGED:<UNIX timestamp>:<holdoff>"
1086 *
1087 * @param string $key Cache key
1088 * @param integer $ttl How long to keep the tombstone [seconds]
1089 * @param integer $holdoff HOLDOFF_* constant controlling how long to ignore sets for this key
1090 * @return bool Success
1091 */
1092 protected function relayPurge( $key, $ttl, $holdoff ) {
1093 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1094 // This handles the mcrouter and the single-DC case
1095 $ok = $this->cache->set( $key,
1096 $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
1097 $ttl
1098 );
1099 } else {
1100 $event = $this->cache->modifySimpleRelayEvent( [
1101 'cmd' => 'set',
1102 'key' => $key,
1103 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1104 'ttl' => max( $ttl, 1 ),
1105 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1106 ] );
1107
1108 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1109 if ( !$ok ) {
1110 $this->lastRelayError = self::ERR_RELAY;
1111 }
1112 }
1113
1114 return $ok;
1115 }
1116
1117 /**
1118 * Do the actual async bus delete of a key
1119 *
1120 * @param string $key Cache key
1121 * @return bool Success
1122 */
1123 protected function relayDelete( $key ) {
1124 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1125 // This handles the mcrouter and the single-DC case
1126 $ok = $this->cache->delete( $key );
1127 } else {
1128 $event = $this->cache->modifySimpleRelayEvent( [
1129 'cmd' => 'delete',
1130 'key' => $key,
1131 ] );
1132
1133 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1134 if ( !$ok ) {
1135 $this->lastRelayError = self::ERR_RELAY;
1136 }
1137 }
1138
1139 return $ok;
1140 }
1141
1142 /**
1143 * Check if a key should be regenerated (using random probability)
1144 *
1145 * This returns false if $curTTL >= $lowTTL. Otherwise, the chance
1146 * of returning true increases steadily from 0% to 100% as the $curTTL
1147 * moves from $lowTTL to 0 seconds. This handles widely varying
1148 * levels of cache access traffic.
1149 *
1150 * @param float $curTTL Approximate TTL left on the key if present
1151 * @param float $lowTTL Consider a refresh when $curTTL is less than this
1152 * @return bool
1153 */
1154 protected function worthRefresh( $curTTL, $lowTTL ) {
1155 if ( $curTTL >= $lowTTL ) {
1156 return false;
1157 } elseif ( $curTTL <= 0 ) {
1158 return true;
1159 }
1160
1161 $chance = ( 1 - $curTTL / $lowTTL );
1162
1163 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1164 }
1165
1166 /**
1167 * Check whether $value is appropriately versioned and not older than $minTime (if set)
1168 *
1169 * @param array $value
1170 * @param bool $versioned
1171 * @param float $asOf The time $value was generated
1172 * @param float $minTime The last time the main value was generated (0.0 if unknown)
1173 * @return bool
1174 */
1175 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1176 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1177 return false;
1178 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1179 return false;
1180 }
1181
1182 return true;
1183 }
1184
1185 /**
1186 * Do not use this method outside WANObjectCache
1187 *
1188 * @param mixed $value
1189 * @param integer $ttl [0=forever]
1190 * @param float $now Unix Current timestamp just before calling set()
1191 * @return array
1192 */
1193 protected function wrap( $value, $ttl, $now ) {
1194 return [
1195 self::FLD_VERSION => self::VERSION,
1196 self::FLD_VALUE => $value,
1197 self::FLD_TTL => $ttl,
1198 self::FLD_TIME => $now
1199 ];
1200 }
1201
1202 /**
1203 * Do not use this method outside WANObjectCache
1204 *
1205 * @param array|string|bool $wrapped
1206 * @param float $now Unix Current timestamp (preferrably pre-query)
1207 * @return array (mixed; false if absent/invalid, current time left)
1208 */
1209 protected function unwrap( $wrapped, $now ) {
1210 // Check if the value is a tombstone
1211 $purge = self::parsePurgeValue( $wrapped );
1212 if ( $purge !== false ) {
1213 // Purged values should always have a negative current $ttl
1214 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1215 return [ false, $curTTL ];
1216 }
1217
1218 if ( !is_array( $wrapped ) // not found
1219 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1220 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1221 ) {
1222 return [ false, null ];
1223 }
1224
1225 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1226 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1227 // Treat as expired, with the cache time as the expiration
1228 $age = $now - $wrapped[self::FLD_TIME];
1229 $curTTL = min( -$age, self::TINY_NEGATIVE );
1230 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1231 // Get the approximate time left on the key
1232 $age = $now - $wrapped[self::FLD_TIME];
1233 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1234 } else {
1235 // Key had no TTL, so the time left is unbounded
1236 $curTTL = INF;
1237 }
1238
1239 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1240 }
1241
1242 /**
1243 * @param array $keys
1244 * @param string $prefix
1245 * @return string[]
1246 */
1247 protected static function prefixCacheKeys( array $keys, $prefix ) {
1248 $res = [];
1249 foreach ( $keys as $key ) {
1250 $res[] = $prefix . $key;
1251 }
1252
1253 return $res;
1254 }
1255
1256 /**
1257 * @param string $value Wrapped value like "PURGED:<timestamp>:<holdoff>"
1258 * @return array|bool Array containing a UNIX timestamp (float) and holdoff period (integer),
1259 * or false if value isn't a valid purge value
1260 */
1261 protected static function parsePurgeValue( $value ) {
1262 if ( !is_string( $value ) ) {
1263 return false;
1264 }
1265 $segments = explode( ':', $value, 3 );
1266 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1267 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1268 ) {
1269 return false;
1270 }
1271 if ( !isset( $segments[2] ) ) {
1272 // Back-compat with old purge values without holdoff
1273 $segments[2] = self::HOLDOFF_TTL;
1274 }
1275 return [
1276 self::FLD_TIME => (float)$segments[1],
1277 self::FLD_HOLDOFF => (int)$segments[2],
1278 ];
1279 }
1280
1281 /**
1282 * @param float $timestamp
1283 * @param int $holdoff In seconds
1284 * @return string Wrapped purge value
1285 */
1286 protected function makePurgeValue( $timestamp, $holdoff ) {
1287 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1288 }
1289 }