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 callback|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 int[] Map of (ATTR_* class constant => QOS_* class constant) */
85 protected $attrMap = [];
87 /** Possible values for getLastError() */
88 const ERR_NONE
= 0; // no error
89 const ERR_NO_RESPONSE
= 1; // no response
90 const ERR_UNREACHABLE
= 2; // can't connect
91 const ERR_UNEXPECTED
= 3; // response gave some error
93 /** Bitfield constants for get()/getMulti() */
94 const READ_LATEST
= 1; // use latest data for replicated stores
95 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
96 /** Bitfield constants for set()/merge() */
97 const WRITE_SYNC
= 1; // synchronously write to all locations for replicated stores
98 const WRITE_CACHE_ONLY
= 2; // Only change state of the in-memory cache
102 * - logger: Psr\Log\LoggerInterface instance
103 * - keyspace: Default keyspace for $this->makeKey()
104 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
105 * In CLI mode, it should run the task immediately.
106 * - reportDupes: Whether to emit warning log messages for all keys that were
107 * requested more than once (requires an asyncHandler).
108 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
109 * @param array $params
111 public function __construct( array $params = [] ) {
112 if ( isset( $params['logger'] ) ) {
113 $this->setLogger( $params['logger'] );
115 $this->setLogger( new NullLogger() );
118 if ( isset( $params['keyspace'] ) ) {
119 $this->keyspace
= $params['keyspace'];
122 $this->asyncHandler
= isset( $params['asyncHandler'] )
123 ?
$params['asyncHandler']
126 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
127 $this->reportDupes
= true;
130 $this->syncTimeout
= isset( $params['syncTimeout'] ) ?
$params['syncTimeout'] : 3;
134 * @param LoggerInterface $logger
137 public function setLogger( LoggerInterface
$logger ) {
138 $this->logger
= $logger;
144 public function setDebug( $bool ) {
145 $this->debugMode
= $bool;
149 * Get an item with the given key, regenerating and setting it if not found
151 * If the callback returns false, then nothing is stored.
154 * @param int $ttl Time-to-live (seconds)
155 * @param callable $callback Callback that derives the new value
156 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
157 * @return mixed The cached value if found or the result of $callback otherwise
160 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
161 $value = $this->get( $key, $flags );
163 if ( $value === false ) {
164 if ( !is_callable( $callback ) ) {
165 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
167 $value = call_user_func( $callback );
168 if ( $value !== false ) {
169 $this->set( $key, $value, $ttl );
177 * Get an item with the given key
179 * If the key includes a deterministic input hash (e.g. the key can only have
180 * the correct value) or complete staleness checks are handled by the caller
181 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
182 * This lets tiered backends know they can safely upgrade a cached value to
183 * higher tiers using standard TTLs.
186 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
187 * @param int $oldFlags [unused]
188 * @return mixed Returns false on failure and if the item does not exist
190 public function get( $key, $flags = 0, $oldFlags = null ) {
191 // B/C for ( $key, &$casToken = null, $flags = 0 )
192 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
194 $this->trackDuplicateKeys( $key );
196 return $this->doGet( $key, $flags );
200 * Track the number of times that a given key has been used.
203 private function trackDuplicateKeys( $key ) {
204 if ( !$this->reportDupes
) {
208 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
209 // Track that we have seen this key. This N-1 counting style allows
210 // easy filtering with array_filter() later.
211 $this->duplicateKeyLookups
[$key] = 0;
213 $this->duplicateKeyLookups
[$key] +
= 1;
215 if ( $this->dupeTrackScheduled
=== false ) {
216 $this->dupeTrackScheduled
= true;
217 // Schedule a callback that logs keys processed more than once by get().
218 call_user_func( $this->asyncHandler
, function () {
219 $dups = array_filter( $this->duplicateKeyLookups
);
220 foreach ( $dups as $key => $count ) {
221 $this->logger
->warning(
222 'Duplicate get(): "{key}" fetched {count} times',
223 // Count is N-1 of the actual lookup count
224 [ 'key' => $key, 'count' => $count +
1, ]
234 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
235 * @return mixed Returns false on failure and if the item does not exist
237 abstract protected function doGet( $key, $flags = 0 );
240 * @note: This method is only needed if merge() uses mergeViaCas()
243 * @param mixed &$casToken
244 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
245 * @return mixed Returns false on failure and if the item does not exist
248 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
249 throw new Exception( __METHOD__
. ' not implemented.' );
256 * @param mixed $value
257 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
258 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
259 * @return bool Success
261 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
267 * @return bool True if the item was deleted or not found, false on failure
269 abstract public function delete( $key );
272 * Merge changes into the existing cache value (possibly creating a new one)
274 * The callback function returns the new value given the current value
275 * (which will be false if not present), and takes the arguments:
276 * (this BagOStuff, cache key, current value, TTL).
277 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
280 * @param callable $callback Callback method to be executed
281 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
282 * @param int $attempts The amount of times to attempt a merge in case of failure
283 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
284 * @return bool Success
285 * @throws InvalidArgumentException
287 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
288 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
292 * @see BagOStuff::merge()
295 * @param callable $callback Callback method to be executed
296 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
297 * @param int $attempts The amount of times to attempt a merge in case of failure
298 * @return bool Success
300 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
302 $this->clearLastError();
303 $reportDupes = $this->reportDupes
;
304 $this->reportDupes
= false;
305 $casToken = null; // passed by reference
306 $currentValue = $this->getWithToken( $key, $casToken, self
::READ_LATEST
);
307 $this->reportDupes
= $reportDupes;
309 if ( $this->getLastError() ) {
310 return false; // don't spam retries (retry only on races)
313 // Derive the new value from the old value
314 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
316 $this->clearLastError();
317 if ( $value === false ) {
318 $success = true; // do nothing
319 } elseif ( $currentValue === false ) {
320 // Try to create the key, failing if it gets created in the meantime
321 $success = $this->add( $key, $value, $exptime );
323 // Try to update the key, failing if it gets changed in the meantime
324 $success = $this->cas( $casToken, $key, $value, $exptime );
326 if ( $this->getLastError() ) {
327 return false; // IO error; don't spam retries
329 } while ( !$success && --$attempts );
335 * Check and set an item
337 * @param mixed $casToken
339 * @param mixed $value
340 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
341 * @return bool Success
344 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
345 throw new Exception( "CAS is not implemented in " . __CLASS__
);
349 * @see BagOStuff::merge()
352 * @param callable $callback Callback method to be executed
353 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
354 * @param int $attempts The amount of times to attempt a merge in case of failure
355 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
356 * @return bool Success
358 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
359 if ( !$this->lock( $key, 6 ) ) {
363 $this->clearLastError();
364 $reportDupes = $this->reportDupes
;
365 $this->reportDupes
= false;
366 $currentValue = $this->get( $key, self
::READ_LATEST
);
367 $this->reportDupes
= $reportDupes;
369 if ( $this->getLastError() ) {
372 // Derive the new value from the old value
373 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
374 if ( $value === false ) {
375 $success = true; // do nothing
377 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
381 if ( !$this->unlock( $key ) ) {
382 // this should never happen
383 trigger_error( "Could not release lock for key '$key'." );
390 * Reset the TTL on a key if it exists
394 * @return bool Success Returns false if there is no key
397 public function changeTTL( $key, $expiry = 0 ) {
398 $value = $this->get( $key );
400 return ( $value === false ) ?
false : $this->set( $key, $value, $expiry );
404 * Acquire an advisory lock on a key string
406 * Note that if reentry is enabled, duplicate calls ignore $expiry
409 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
410 * @param int $expiry Lock expiry [optional]; 1 day maximum
411 * @param string $rclass Allow reentry if set and the current lock used this value
412 * @return bool Success
414 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
415 // Avoid deadlocks and allow lock reentry if specified
416 if ( isset( $this->locks
[$key] ) ) {
417 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
418 ++
$this->locks
[$key]['depth'];
425 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
426 $loop = new WaitConditionLoop(
427 function () use ( $key, $timeout, $expiry ) {
428 $this->clearLastError();
429 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
430 return true; // locked!
431 } elseif ( $this->getLastError() ) {
432 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
435 return WaitConditionLoop
::CONDITION_CONTINUE
;
440 $locked = ( $loop->invoke() === $loop::CONDITION_REACHED
);
442 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
449 * Release an advisory lock on a key string
452 * @return bool Success
454 public function unlock( $key ) {
455 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
456 unset( $this->locks
[$key] );
458 return $this->delete( "{$key}:lock" );
465 * Get a lightweight exclusive self-unlocking lock
467 * Note that the same lock cannot be acquired twice.
469 * This is useful for task de-duplication or to avoid obtrusive
470 * (though non-corrupting) DB errors like INSERT key conflicts
471 * or deadlocks when using LOCK IN SHARE MODE.
474 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
475 * @param int $expiry Lock expiry [optional]; 1 day maximum
476 * @param string $rclass Allow reentry if set and the current lock used this value
477 * @return ScopedCallback|null Returns null on failure
480 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
481 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
483 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
487 $lSince = microtime( true ); // lock timestamp
489 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
490 $latency = 0.050; // latency skew (err towards keeping lock present)
491 $age = ( microtime( true ) - $lSince +
$latency );
492 if ( ( $age +
$latency ) >= $expiry ) {
493 $this->logger
->warning( "Lock for $key held too long ($age sec)." );
494 return; // expired; it's not "safe" to delete the key
496 $this->unlock( $key );
501 * Delete all objects expiring before a certain date.
502 * @param string $date The reference date in MW format
503 * @param callable|bool $progressCallback Optional, a function which will be called
504 * regularly during long-running operations with the percentage progress
505 * as the first parameter.
507 * @return bool Success, false if unimplemented
509 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
515 * Get an associative array containing the item for each of the keys that have items.
516 * @param array $keys List of strings
517 * @param int $flags Bitfield; supports READ_LATEST [optional]
520 public function getMulti( array $keys, $flags = 0 ) {
522 foreach ( $keys as $key ) {
523 $val = $this->get( $key );
524 if ( $val !== false ) {
533 * @param array $data $key => $value assoc array
534 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
535 * @return bool Success
538 public function setMulti( array $data, $exptime = 0 ) {
540 foreach ( $data as $key => $value ) {
541 if ( !$this->set( $key, $value, $exptime ) ) {
550 * @param mixed $value
551 * @param int $exptime
552 * @return bool Success
554 public function add( $key, $value, $exptime = 0 ) {
555 if ( $this->get( $key ) === false ) {
556 return $this->set( $key, $value, $exptime );
558 return false; // key already set
562 * Increase stored value of $key by $value while preserving its TTL
563 * @param string $key Key to increase
564 * @param int $value Value to add to $key (Default 1)
565 * @return int|bool New value or false on failure
567 public function incr( $key, $value = 1 ) {
568 if ( !$this->lock( $key ) ) {
571 $n = $this->get( $key );
572 if ( $this->isInteger( $n ) ) { // key exists?
573 $n +
= intval( $value );
574 $this->set( $key, max( 0, $n ) ); // exptime?
578 $this->unlock( $key );
584 * Decrease stored value of $key by $value while preserving its TTL
587 * @return int|bool New value or false on failure
589 public function decr( $key, $value = 1 ) {
590 return $this->incr( $key, - $value );
594 * Increase stored value of $key by $value while preserving its TTL
596 * This will create the key with value $init and TTL $ttl instead if not present
602 * @return int|bool New value or false on failure
605 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
606 $newValue = $this->incr( $key, $value );
607 if ( $newValue === false ) {
608 // No key set; initialize
609 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
611 if ( $newValue === false ) {
612 // Raced out initializing; increment
613 $newValue = $this->incr( $key, $value );
620 * Get the "last error" registered; clearLastError() should be called manually
621 * @return int ERR_* constant for the "last error" registry
624 public function getLastError() {
625 return $this->lastError
;
629 * Clear the "last error" registry
632 public function clearLastError() {
633 $this->lastError
= self
::ERR_NONE
;
637 * Set the "last error" registry
638 * @param int $err ERR_* constant
641 protected function setLastError( $err ) {
642 $this->lastError
= $err;
646 * Let a callback be run to avoid wasting time on special blocking calls
648 * The callbacks may or may not be called ever, in any particular order.
649 * They are likely to be invoked when something WRITE_SYNC is used used.
650 * They should follow a caching pattern as shown below, so that any code
651 * using the word will get it's result no matter what happens.
654 * $workCallback = function () use ( &$result ) {
662 * @param callable $workCallback
665 public function addBusyCallback( callable
$workCallback ) {
666 $this->busyCallbacks
[] = $workCallback;
670 * Modify a cache update operation array for EventRelayer::notify()
672 * This is used for relayed writes, e.g. for broadcasting a change
673 * to multiple data-centers. If the array contains a 'val' field
674 * then the command involves setting a key to that value. Note that
675 * for simplicity, 'val' is always a simple scalar value. This method
676 * is used to possibly serialize the value and add any cache-specific
677 * key/values needed for the relayer daemon (e.g. memcached flags).
679 * @param array $event
683 public function modifySimpleRelayEvent( array $event ) {
688 * @param string $text
690 protected function debug( $text ) {
691 if ( $this->debugMode
) {
692 $this->logger
->debug( "{class} debug: $text", [
693 'class' => static::class,
699 * Convert an optionally relative time to an absolute time
700 * @param int $exptime
703 protected function convertExpiry( $exptime ) {
704 if ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) ) {
705 return time() +
$exptime;
712 * Convert an optionally absolute expiry time to a relative time. If an
713 * absolute time is specified which is in the past, use a short expiry time.
715 * @param int $exptime
718 protected function convertToRelative( $exptime ) {
719 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
721 if ( $exptime <= 0 ) {
731 * Check if a value is an integer
733 * @param mixed $value
736 protected function isInteger( $value ) {
737 return ( is_int( $value ) ||
ctype_digit( $value ) );
741 * Construct a cache key.
744 * @param string $keyspace
746 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
748 public function makeKeyInternal( $keyspace, $args ) {
750 foreach ( $args as $arg ) {
751 $arg = str_replace( ':', '%3A', $arg );
752 $key = $key . ':' . $arg;
754 return strtr( $key, ' ', '_' );
758 * Make a global cache key.
761 * @param string $class Key class
762 * @param string $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 $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 isset( $this->attrMap
[$flag] ) ?
$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 );