3 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
4 * https://www.mediawiki.org/
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
26 * @defgroup Cache Cache
29 use Psr\Log\LoggerAwareInterface
;
30 use Psr\Log\LoggerInterface
;
31 use Psr\Log\NullLogger
;
32 use Wikimedia\ScopedCallback
;
33 use Wikimedia\WaitConditionLoop
;
36 * Class representing a cache/ephemeral data store
38 * This interface is intended to be more or less compatible with the PHP memcached client.
40 * Instances of this class should be created with an intended access scope, such as:
41 * - a) A single PHP thread on a server (e.g. stored in a PHP variable)
42 * - b) A single application server (e.g. stored in APC or sqlite)
43 * - c) All application servers in datacenter (e.g. stored in memcached or mysql)
44 * - d) All application servers in all datacenters (e.g. stored via mcrouter or dynomite)
46 * Callers should use the proper factory methods that yield BagOStuff instances. Site admins
47 * should make sure the configuration for those factory methods matches their access scope.
48 * BagOStuff subclasses have widely varying levels of support for replication features.
50 * For any given instance, methods like lock(), unlock(), merge(), and set() with WRITE_SYNC
51 * should semantically operate over its entire access scope; any nodes/threads in that scope
52 * should serialize appropriately when using them. Likewise, a call to get() with READ_LATEST
53 * from one node in its access scope should reflect the prior changes of any other node its access
54 * scope. Any get() should reflect the changes of any prior set() with WRITE_SYNC.
58 abstract class BagOStuff
implements IExpiringStore
, LoggerAwareInterface
{
59 /** @var array[] Lock tracking */
60 protected $locks = [];
61 /** @var int ERR_* class constant */
62 protected $lastError = self
::ERR_NONE
;
64 protected $keyspace = 'local';
65 /** @var LoggerInterface */
67 /** @var callable|null */
68 protected $asyncHandler;
69 /** @var int Seconds */
70 protected $syncTimeout;
73 private $debugMode = false;
75 private $duplicateKeyLookups = [];
77 private $reportDupes = false;
79 private $dupeTrackScheduled = false;
81 /** @var callable[] */
82 protected $busyCallbacks = [];
84 /** @var float|null */
85 private $wallClockOverride;
87 /** @var int[] Map of (ATTR_* class constant => QOS_* class constant) */
88 protected $attrMap = [];
90 /** Bitfield constants for get()/getMulti() */
91 const READ_LATEST
= 1; // use latest data for replicated stores
92 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
93 /** Bitfield constants for set()/merge() */
94 const WRITE_SYNC
= 4; // synchronously write to all locations for replicated stores
95 const WRITE_CACHE_ONLY
= 8; // Only change state of the in-memory cache
99 * - logger: Psr\Log\LoggerInterface instance
100 * - keyspace: Default keyspace for $this->makeKey()
101 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
102 * In CLI mode, it should run the task immediately.
103 * - reportDupes: Whether to emit warning log messages for all keys that were
104 * requested more than once (requires an asyncHandler).
105 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
106 * @param array $params
108 public function __construct( array $params = [] ) {
109 $this->setLogger( $params['logger'] ??
new NullLogger() );
111 if ( isset( $params['keyspace'] ) ) {
112 $this->keyspace
= $params['keyspace'];
115 $this->asyncHandler
= $params['asyncHandler'] ??
null;
117 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
118 $this->reportDupes
= true;
121 $this->syncTimeout
= $params['syncTimeout'] ??
3;
125 * @param LoggerInterface $logger
128 public function setLogger( LoggerInterface
$logger ) {
129 $this->logger
= $logger;
135 public function setDebug( $bool ) {
136 $this->debugMode
= $bool;
140 * Get an item with the given key, regenerating and setting it if not found
142 * Nothing is stored nor deleted if the callback returns false
145 * @param int $ttl Time-to-live (seconds)
146 * @param callable $callback Callback that derives the new value
147 * @param int $flags Bitfield of BagOStuff::READ_* or BagOStuff::WRITE_* constants [optional]
148 * @return mixed The cached value if found or the result of $callback otherwise
151 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
152 $value = $this->get( $key, $flags );
154 if ( $value === false ) {
155 if ( !is_callable( $callback ) ) {
156 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
158 $value = call_user_func( $callback );
159 if ( $value !== false ) {
160 $this->set( $key, $value, $ttl, $flags );
168 * Get an item with the given key
170 * If the key includes a deterministic input hash (e.g. the key can only have
171 * the correct value) or complete staleness checks are handled by the caller
172 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
173 * This lets tiered backends know they can safely upgrade a cached value to
174 * higher tiers using standard TTLs.
177 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
178 * @return mixed Returns false on failure or if the item does not exist
180 public function get( $key, $flags = 0 ) {
181 $this->trackDuplicateKeys( $key );
183 return $this->doGet( $key, $flags );
187 * Track the number of times that a given key has been used.
190 private function trackDuplicateKeys( $key ) {
191 if ( !$this->reportDupes
) {
195 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
196 // Track that we have seen this key. This N-1 counting style allows
197 // easy filtering with array_filter() later.
198 $this->duplicateKeyLookups
[$key] = 0;
200 $this->duplicateKeyLookups
[$key] +
= 1;
202 if ( $this->dupeTrackScheduled
=== false ) {
203 $this->dupeTrackScheduled
= true;
204 // Schedule a callback that logs keys processed more than once by get().
205 call_user_func( $this->asyncHandler
, function () {
206 $dups = array_filter( $this->duplicateKeyLookups
);
207 foreach ( $dups as $key => $count ) {
208 $this->logger
->warning(
209 'Duplicate get(): "{key}" fetched {count} times',
210 // Count is N-1 of the actual lookup count
211 [ 'key' => $key, 'count' => $count +
1, ]
221 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
222 * @param mixed|null &$casToken Token to use for check-and-set comparisons
223 * @return mixed Returns false on failure or if the item does not exist
225 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
231 * @param mixed $value
232 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
233 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
234 * @return bool Success
236 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
242 * @return bool True if the item was deleted or not found, false on failure
243 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
245 abstract public function delete( $key, $flags = 0 );
248 * Insert an item if it does not already exist
251 * @param mixed $value
252 * @param int $exptime
253 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
254 * @return bool Success
256 abstract public function add( $key, $value, $exptime = 0, $flags = 0 );
259 * Merge changes into the existing cache value (possibly creating a new one)
261 * The callback function returns the new value given the current value
262 * (which will be false if not present), and takes the arguments:
263 * (this BagOStuff, cache key, current value, TTL).
264 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
265 * Nothing is stored nor deleted if the callback returns false.
268 * @param callable $callback Callback method to be executed
269 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
270 * @param int $attempts The amount of times to attempt a merge in case of failure
271 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
272 * @return bool Success
273 * @throws InvalidArgumentException
275 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
276 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
280 * @see BagOStuff::merge()
283 * @param callable $callback Callback method to be executed
284 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
285 * @param int $attempts The amount of times to attempt a merge in case of failure
286 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
287 * @return bool Success
289 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
291 $this->clearLastError();
292 $reportDupes = $this->reportDupes
;
293 $this->reportDupes
= false;
294 $casToken = null; // passed by reference
295 $currentValue = $this->doGet( $key, self
::READ_LATEST
, $casToken );
296 $this->reportDupes
= $reportDupes;
298 if ( $this->getLastError() ) {
299 $this->logger
->warning(
300 __METHOD__
. ' failed due to I/O error on get() for {key}.',
304 return false; // don't spam retries (retry only on races)
307 // Derive the new value from the old value
308 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
309 $hadNoCurrentValue = ( $currentValue === false );
310 unset( $currentValue ); // free RAM in case the value is large
312 $this->clearLastError();
313 if ( $value === false ) {
314 $success = true; // do nothing
315 } elseif ( $hadNoCurrentValue ) {
316 // Try to create the key, failing if it gets created in the meantime
317 $success = $this->add( $key, $value, $exptime, $flags );
319 // Try to update the key, failing if it gets changed in the meantime
320 $success = $this->cas( $casToken, $key, $value, $exptime, $flags );
322 if ( $this->getLastError() ) {
323 $this->logger
->warning(
324 __METHOD__
. ' failed due to I/O error for {key}.',
328 return false; // IO error; don't spam retries
330 } while ( !$success && --$attempts );
336 * Check and set an item
338 * @param mixed $casToken
340 * @param mixed $value
341 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
342 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
343 * @return bool Success
346 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
347 if ( !$this->lock( $key, 0 ) ) {
348 return false; // non-blocking
351 $curCasToken = null; // passed by reference
352 $this->doGet( $key, self
::READ_LATEST
, $curCasToken );
353 if ( $casToken === $curCasToken ) {
354 $success = $this->set( $key, $value, $exptime, $flags );
357 __METHOD__
. ' failed due to race condition for {key}.',
361 $success = false; // mismatched or failed
364 $this->unlock( $key );
370 * Change the expiration on a key if it exists
372 * If an expiry in the past is given then the key will immediately be expired
375 * @param int $expiry TTL or UNIX timestamp
376 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
377 * @return bool Success Returns false on failure or if the item does not exist
380 public function changeTTL( $key, $expiry = 0, $flags = 0 ) {
385 function ( $cache, $ttl, $currentValue ) use ( &$found ) {
386 $found = ( $currentValue !== false );
388 return $currentValue; // nothing is written if this is false
395 return ( $ok && $found );
399 * Acquire an advisory lock on a key string
401 * Note that if reentry is enabled, duplicate calls ignore $expiry
404 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
405 * @param int $expiry Lock expiry [optional]; 1 day maximum
406 * @param string $rclass Allow reentry if set and the current lock used this value
407 * @return bool Success
409 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
410 // Avoid deadlocks and allow lock reentry if specified
411 if ( isset( $this->locks
[$key] ) ) {
412 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
413 ++
$this->locks
[$key]['depth'];
421 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
422 $loop = new WaitConditionLoop(
423 function () use ( $key, $expiry, $fname ) {
424 $this->clearLastError();
425 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
426 return WaitConditionLoop
::CONDITION_REACHED
; // locked!
427 } elseif ( $this->getLastError() ) {
428 $this->logger
->warning(
429 $fname . ' failed due to I/O error for {key}.',
433 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
436 return WaitConditionLoop
::CONDITION_CONTINUE
;
441 $code = $loop->invoke();
442 $locked = ( $code === $loop::CONDITION_REACHED
);
444 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
445 } elseif ( $code === $loop::CONDITION_TIMED_OUT
) {
446 $this->logger
->warning(
447 "$fname failed due to timeout for {key}.",
448 [ 'key' => $key, 'timeout' => $timeout ]
456 * Release an advisory lock on a key string
459 * @return bool Success
461 public function unlock( $key ) {
462 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
463 unset( $this->locks
[$key] );
465 $ok = $this->delete( "{$key}:lock" );
467 $this->logger
->warning(
468 __METHOD__
. ' failed to release lock for {key}.',
480 * Get a lightweight exclusive self-unlocking lock
482 * Note that the same lock cannot be acquired twice.
484 * This is useful for task de-duplication or to avoid obtrusive
485 * (though non-corrupting) DB errors like INSERT key conflicts
486 * or deadlocks when using LOCK IN SHARE MODE.
489 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
490 * @param int $expiry Lock expiry [optional]; 1 day maximum
491 * @param string $rclass Allow reentry if set and the current lock used this value
492 * @return ScopedCallback|null Returns null on failure
495 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
496 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
498 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
502 $lSince = $this->getCurrentTime(); // lock timestamp
504 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
505 $latency = 0.050; // latency skew (err towards keeping lock present)
506 $age = ( $this->getCurrentTime() - $lSince +
$latency );
507 if ( ( $age +
$latency ) >= $expiry ) {
508 $this->logger
->warning(
509 "Lock for {key} held too long ({age} sec).",
510 [ 'key' => $key, 'age' => $age ]
512 return; // expired; it's not "safe" to delete the key
514 $this->unlock( $key );
519 * Delete all objects expiring before a certain date.
520 * @param string $date The reference date in MW format
521 * @param callable|bool $progressCallback Optional, a function which will be called
522 * regularly during long-running operations with the percentage progress
523 * as the first parameter.
525 * @return bool Success, false if unimplemented
527 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
533 * Get an associative array containing the item for each of the keys that have items.
534 * @param string[] $keys List of keys
535 * @param int $flags Bitfield; supports READ_LATEST [optional]
538 public function getMulti( array $keys, $flags = 0 ) {
540 foreach ( $keys as $key ) {
541 $val = $this->get( $key, $flags );
542 if ( $val !== false ) {
551 * Batch insertion/replace
552 * @param mixed[] $data Map of (key => value)
553 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
554 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
555 * @return bool Success
558 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
560 foreach ( $data as $key => $value ) {
561 if ( !$this->set( $key, $value, $exptime, $flags ) ) {
571 * @param string[] $keys List of keys
572 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
573 * @return bool Success
576 public function deleteMulti( array $keys, $flags = 0 ) {
578 foreach ( $keys as $key ) {
579 $res = $this->delete( $key, $flags ) && $res;
586 * Increase stored value of $key by $value while preserving its TTL
587 * @param string $key Key to increase
588 * @param int $value Value to add to $key (default: 1) [optional]
589 * @return int|bool New value or false on failure
591 abstract public function incr( $key, $value = 1 );
594 * Decrease stored value of $key by $value while preserving its TTL
596 * @param int $value Value to subtract from $key (default: 1) [optional]
597 * @return int|bool New value or false on failure
599 public function decr( $key, $value = 1 ) {
600 return $this->incr( $key, - $value );
604 * Increase stored value of $key by $value while preserving its TTL
606 * This will create the key with value $init and TTL $ttl instead if not present
612 * @return int|bool New value or false on failure
615 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
616 $this->clearLastError();
617 $newValue = $this->incr( $key, $value );
618 if ( $newValue === false && !$this->getLastError() ) {
619 // No key set; initialize
620 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
621 if ( $newValue === false && !$this->getLastError() ) {
622 // Raced out initializing; increment
623 $newValue = $this->incr( $key, $value );
631 * Get the "last error" registered; clearLastError() should be called manually
632 * @return int ERR_* constant for the "last error" registry
635 public function getLastError() {
636 return $this->lastError
;
640 * Clear the "last error" registry
643 public function clearLastError() {
644 $this->lastError
= self
::ERR_NONE
;
648 * Set the "last error" registry
649 * @param int $err ERR_* constant
652 protected function setLastError( $err ) {
653 $this->lastError
= $err;
657 * Let a callback be run to avoid wasting time on special blocking calls
659 * The callbacks may or may not be called ever, in any particular order.
660 * They are likely to be invoked when something WRITE_SYNC is used used.
661 * They should follow a caching pattern as shown below, so that any code
662 * using the work will get it's result no matter what happens.
665 * $workCallback = function () use ( &$result ) {
673 * @param callable $workCallback
676 public function addBusyCallback( callable
$workCallback ) {
677 $this->busyCallbacks
[] = $workCallback;
681 * @param string $text
683 protected function debug( $text ) {
684 if ( $this->debugMode
) {
685 $this->logger
->debug( "{class} debug: $text", [
686 'class' => static::class,
692 * @param int $exptime
695 protected function expiryIsRelative( $exptime ) {
696 return ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) );
700 * Convert an optionally relative time to an absolute time
701 * @param int $exptime
704 protected function convertToExpiry( $exptime ) {
705 if ( $this->expiryIsRelative( $exptime ) ) {
706 return (int)$this->getCurrentTime() +
$exptime;
713 * Convert an optionally absolute expiry time to a relative time. If an
714 * absolute time is specified which is in the past, use a short expiry time.
716 * @param int $exptime
719 protected function convertToRelative( $exptime ) {
720 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
721 $exptime -= (int)$this->getCurrentTime();
722 if ( $exptime <= 0 ) {
732 * Check if a value is an integer
734 * @param mixed $value
737 protected function isInteger( $value ) {
738 return ( is_int( $value ) ||
ctype_digit( $value ) );
742 * Construct a cache key.
745 * @param string $keyspace
747 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
749 public function makeKeyInternal( $keyspace, $args ) {
751 foreach ( $args as $arg ) {
752 $key .= ':' . str_replace( ':', '%3A', $arg );
754 return strtr( $key, ' ', '_' );
758 * Make a global cache key.
761 * @param string $class Key class
762 * @param string|null $component [optional] Key component (starting with a key collection name)
763 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
765 public function makeGlobalKey( $class, $component = null ) {
766 return $this->makeKeyInternal( 'global', func_get_args() );
770 * Make a cache key, scoped to this instance's keyspace.
773 * @param string $class Key class
774 * @param string|null $component [optional] Key component (starting with a key collection name)
775 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
777 public function makeKey( $class, $component = null ) {
778 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
782 * @param int $flag ATTR_* class constant
783 * @return int QOS_* class constant
786 public function getQoS( $flag ) {
787 return $this->attrMap
[$flag] ?? self
::QOS_UNKNOWN
;
791 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
793 * @param BagOStuff[] $bags
794 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
796 protected function mergeFlagMaps( array $bags ) {
798 foreach ( $bags as $bag ) {
799 foreach ( $bag->attrMap
as $attr => $rank ) {
800 if ( isset( $map[$attr] ) ) {
801 $map[$attr] = min( $map[$attr], $rank );
812 * @return float UNIX timestamp
813 * @codeCoverageIgnore
815 protected function getCurrentTime() {
816 return $this->wallClockOverride ?
: microtime( true );
820 * @param float|null &$time Mock UNIX timestamp for testing
821 * @codeCoverageIgnore
823 public function setMockTime( &$time ) {
824 $this->wallClockOverride
=& $time;