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 float|null */
85 private $wallClockOverride;
87 /** @var int[] Map of (ATTR_* class constant => QOS_* class constant) */
88 protected $attrMap = [];
90 /** Possible values for getLastError() */
91 const ERR_NONE
= 0; // no error
92 const ERR_NO_RESPONSE
= 1; // no response
93 const ERR_UNREACHABLE
= 2; // can't connect
94 const ERR_UNEXPECTED
= 3; // response gave some error
96 /** Bitfield constants for get()/getMulti() */
97 const READ_LATEST
= 1; // use latest data for replicated stores
98 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
99 /** Bitfield constants for set()/merge() */
100 const WRITE_SYNC
= 1; // synchronously write to all locations for replicated stores
101 const WRITE_CACHE_ONLY
= 2; // Only change state of the in-memory cache
105 * - logger: Psr\Log\LoggerInterface instance
106 * - keyspace: Default keyspace for $this->makeKey()
107 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
108 * In CLI mode, it should run the task immediately.
109 * - reportDupes: Whether to emit warning log messages for all keys that were
110 * requested more than once (requires an asyncHandler).
111 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
112 * @param array $params
114 public function __construct( array $params = [] ) {
115 if ( isset( $params['logger'] ) ) {
116 $this->setLogger( $params['logger'] );
118 $this->setLogger( new NullLogger() );
121 if ( isset( $params['keyspace'] ) ) {
122 $this->keyspace
= $params['keyspace'];
125 $this->asyncHandler
= isset( $params['asyncHandler'] )
126 ?
$params['asyncHandler']
129 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
130 $this->reportDupes
= true;
133 $this->syncTimeout
= isset( $params['syncTimeout'] ) ?
$params['syncTimeout'] : 3;
137 * @param LoggerInterface $logger
140 public function setLogger( LoggerInterface
$logger ) {
141 $this->logger
= $logger;
147 public function setDebug( $bool ) {
148 $this->debugMode
= $bool;
152 * Get an item with the given key, regenerating and setting it if not found
154 * If the callback returns false, then nothing is stored.
157 * @param int $ttl Time-to-live (seconds)
158 * @param callable $callback Callback that derives the new value
159 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
160 * @return mixed The cached value if found or the result of $callback otherwise
163 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
164 $value = $this->get( $key, $flags );
166 if ( $value === false ) {
167 if ( !is_callable( $callback ) ) {
168 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
170 $value = call_user_func( $callback );
171 if ( $value !== false ) {
172 $this->set( $key, $value, $ttl );
180 * Get an item with the given key
182 * If the key includes a deterministic input hash (e.g. the key can only have
183 * the correct value) or complete staleness checks are handled by the caller
184 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
185 * This lets tiered backends know they can safely upgrade a cached value to
186 * higher tiers using standard TTLs.
189 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
190 * @param int $oldFlags [unused]
191 * @return mixed Returns false on failure and if the item does not exist
193 public function get( $key, $flags = 0, $oldFlags = null ) {
194 // B/C for ( $key, &$casToken = null, $flags = 0 )
195 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
197 $this->trackDuplicateKeys( $key );
199 return $this->doGet( $key, $flags );
203 * Track the number of times that a given key has been used.
206 private function trackDuplicateKeys( $key ) {
207 if ( !$this->reportDupes
) {
211 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
212 // Track that we have seen this key. This N-1 counting style allows
213 // easy filtering with array_filter() later.
214 $this->duplicateKeyLookups
[$key] = 0;
216 $this->duplicateKeyLookups
[$key] +
= 1;
218 if ( $this->dupeTrackScheduled
=== false ) {
219 $this->dupeTrackScheduled
= true;
220 // Schedule a callback that logs keys processed more than once by get().
221 call_user_func( $this->asyncHandler
, function () {
222 $dups = array_filter( $this->duplicateKeyLookups
);
223 foreach ( $dups as $key => $count ) {
224 $this->logger
->warning(
225 'Duplicate get(): "{key}" fetched {count} times',
226 // Count is N-1 of the actual lookup count
227 [ 'key' => $key, 'count' => $count +
1, ]
237 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
238 * @return mixed Returns false on failure and if the item does not exist
240 abstract protected function doGet( $key, $flags = 0 );
243 * @note: This method is only needed if merge() uses mergeViaCas()
246 * @param mixed &$casToken
247 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
248 * @return mixed Returns false on failure and if the item does not exist
251 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
252 throw new Exception( __METHOD__
. ' not implemented.' );
259 * @param mixed $value
260 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
261 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
262 * @return bool Success
264 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
270 * @return bool True if the item was deleted or not found, false on failure
272 abstract public function delete( $key );
275 * Merge changes into the existing cache value (possibly creating a new one)
277 * The callback function returns the new value given the current value
278 * (which will be false if not present), and takes the arguments:
279 * (this BagOStuff, cache key, current value, TTL).
280 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
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
288 * @throws InvalidArgumentException
290 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
291 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
295 * @see BagOStuff::merge()
298 * @param callable $callback Callback method to be executed
299 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
300 * @param int $attempts The amount of times to attempt a merge in case of failure
301 * @return bool Success
303 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
305 $this->clearLastError();
306 $reportDupes = $this->reportDupes
;
307 $this->reportDupes
= false;
308 $casToken = null; // passed by reference
309 $currentValue = $this->getWithToken( $key, $casToken, self
::READ_LATEST
);
310 $this->reportDupes
= $reportDupes;
312 if ( $this->getLastError() ) {
313 return false; // don't spam retries (retry only on races)
316 // Derive the new value from the old value
317 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
319 $this->clearLastError();
320 if ( $value === false ) {
321 $success = true; // do nothing
322 } elseif ( $currentValue === false ) {
323 // Try to create the key, failing if it gets created in the meantime
324 $success = $this->add( $key, $value, $exptime );
326 // Try to update the key, failing if it gets changed in the meantime
327 $success = $this->cas( $casToken, $key, $value, $exptime );
329 if ( $this->getLastError() ) {
330 return false; // IO error; don't spam retries
332 } while ( !$success && --$attempts );
338 * Check and set an item
340 * @param mixed $casToken
342 * @param mixed $value
343 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
344 * @return bool Success
347 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
348 throw new Exception( "CAS is not implemented in " . __CLASS__
);
352 * @see BagOStuff::merge()
355 * @param callable $callback Callback method to be executed
356 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
357 * @param int $attempts The amount of times to attempt a merge in case of failure
358 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
359 * @return bool Success
361 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
362 if ( !$this->lock( $key, 6 ) ) {
366 $this->clearLastError();
367 $reportDupes = $this->reportDupes
;
368 $this->reportDupes
= false;
369 $currentValue = $this->get( $key, self
::READ_LATEST
);
370 $this->reportDupes
= $reportDupes;
372 if ( $this->getLastError() ) {
375 // Derive the new value from the old value
376 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
377 if ( $value === false ) {
378 $success = true; // do nothing
380 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
384 if ( !$this->unlock( $key ) ) {
385 // this should never happen
386 trigger_error( "Could not release lock for key '$key'." );
393 * Reset the TTL on a key if it exists
397 * @return bool Success Returns false if there is no key
400 public function changeTTL( $key, $expiry = 0 ) {
401 $value = $this->get( $key );
403 return ( $value === false ) ?
false : $this->set( $key, $value, $expiry );
407 * Acquire an advisory lock on a key string
409 * Note that if reentry is enabled, duplicate calls ignore $expiry
412 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
413 * @param int $expiry Lock expiry [optional]; 1 day maximum
414 * @param string $rclass Allow reentry if set and the current lock used this value
415 * @return bool Success
417 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
418 // Avoid deadlocks and allow lock reentry if specified
419 if ( isset( $this->locks
[$key] ) ) {
420 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
421 ++
$this->locks
[$key]['depth'];
428 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
429 $loop = new WaitConditionLoop(
430 function () use ( $key, $timeout, $expiry ) {
431 $this->clearLastError();
432 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
433 return true; // locked!
434 } elseif ( $this->getLastError() ) {
435 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
438 return WaitConditionLoop
::CONDITION_CONTINUE
;
443 $locked = ( $loop->invoke() === $loop::CONDITION_REACHED
);
445 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
452 * Release an advisory lock on a key string
455 * @return bool Success
457 public function unlock( $key ) {
458 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
459 unset( $this->locks
[$key] );
461 return $this->delete( "{$key}:lock" );
468 * Get a lightweight exclusive self-unlocking lock
470 * Note that the same lock cannot be acquired twice.
472 * This is useful for task de-duplication or to avoid obtrusive
473 * (though non-corrupting) DB errors like INSERT key conflicts
474 * or deadlocks when using LOCK IN SHARE MODE.
477 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
478 * @param int $expiry Lock expiry [optional]; 1 day maximum
479 * @param string $rclass Allow reentry if set and the current lock used this value
480 * @return ScopedCallback|null Returns null on failure
483 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
484 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
486 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
490 $lSince = $this->getCurrentTime(); // lock timestamp
492 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
493 $latency = 0.050; // latency skew (err towards keeping lock present)
494 $age = ( $this->getCurrentTime() - $lSince +
$latency );
495 if ( ( $age +
$latency ) >= $expiry ) {
496 $this->logger
->warning( "Lock for $key held too long ($age sec)." );
497 return; // expired; it's not "safe" to delete the key
499 $this->unlock( $key );
504 * Delete all objects expiring before a certain date.
505 * @param string $date The reference date in MW format
506 * @param callable|bool $progressCallback Optional, a function which will be called
507 * regularly during long-running operations with the percentage progress
508 * as the first parameter.
510 * @return bool Success, false if unimplemented
512 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
518 * Get an associative array containing the item for each of the keys that have items.
519 * @param array $keys List of strings
520 * @param int $flags Bitfield; supports READ_LATEST [optional]
523 public function getMulti( array $keys, $flags = 0 ) {
525 foreach ( $keys as $key ) {
526 $val = $this->get( $key );
527 if ( $val !== false ) {
536 * @param array $data $key => $value assoc array
537 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
538 * @return bool Success
541 public function setMulti( array $data, $exptime = 0 ) {
543 foreach ( $data as $key => $value ) {
544 if ( !$this->set( $key, $value, $exptime ) ) {
553 * @param mixed $value
554 * @param int $exptime
555 * @return bool Success
557 public function add( $key, $value, $exptime = 0 ) {
558 if ( $this->get( $key ) === false ) {
559 return $this->set( $key, $value, $exptime );
561 return false; // key already set
565 * Increase stored value of $key by $value while preserving its TTL
566 * @param string $key Key to increase
567 * @param int $value Value to add to $key (Default 1)
568 * @return int|bool New value or false on failure
570 public function incr( $key, $value = 1 ) {
571 if ( !$this->lock( $key ) ) {
574 $n = $this->get( $key );
575 if ( $this->isInteger( $n ) ) { // key exists?
576 $n +
= intval( $value );
577 $this->set( $key, max( 0, $n ) ); // exptime?
581 $this->unlock( $key );
587 * Decrease stored value of $key by $value while preserving its TTL
590 * @return int|bool New value or false on failure
592 public function decr( $key, $value = 1 ) {
593 return $this->incr( $key, - $value );
597 * Increase stored value of $key by $value while preserving its TTL
599 * This will create the key with value $init and TTL $ttl instead if not present
605 * @return int|bool New value or false on failure
608 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
609 $newValue = $this->incr( $key, $value );
610 if ( $newValue === false ) {
611 // No key set; initialize
612 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
614 if ( $newValue === false ) {
615 // Raced out initializing; increment
616 $newValue = $this->incr( $key, $value );
623 * Get the "last error" registered; clearLastError() should be called manually
624 * @return int ERR_* constant for the "last error" registry
627 public function getLastError() {
628 return $this->lastError
;
632 * Clear the "last error" registry
635 public function clearLastError() {
636 $this->lastError
= self
::ERR_NONE
;
640 * Set the "last error" registry
641 * @param int $err ERR_* constant
644 protected function setLastError( $err ) {
645 $this->lastError
= $err;
649 * Let a callback be run to avoid wasting time on special blocking calls
651 * The callbacks may or may not be called ever, in any particular order.
652 * They are likely to be invoked when something WRITE_SYNC is used used.
653 * They should follow a caching pattern as shown below, so that any code
654 * using the word will get it's result no matter what happens.
657 * $workCallback = function () use ( &$result ) {
665 * @param callable $workCallback
668 public function addBusyCallback( callable
$workCallback ) {
669 $this->busyCallbacks
[] = $workCallback;
673 * Modify a cache update operation array for EventRelayer::notify()
675 * This is used for relayed writes, e.g. for broadcasting a change
676 * to multiple data-centers. If the array contains a 'val' field
677 * then the command involves setting a key to that value. Note that
678 * for simplicity, 'val' is always a simple scalar value. This method
679 * is used to possibly serialize the value and add any cache-specific
680 * key/values needed for the relayer daemon (e.g. memcached flags).
682 * @param array $event
686 public function modifySimpleRelayEvent( array $event ) {
691 * @param string $text
693 protected function debug( $text ) {
694 if ( $this->debugMode
) {
695 $this->logger
->debug( "{class} debug: $text", [
696 'class' => static::class,
702 * Convert an optionally relative time to an absolute time
703 * @param int $exptime
706 protected function convertExpiry( $exptime ) {
707 if ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) ) {
708 return (int)$this->getCurrentTime() +
$exptime;
715 * Convert an optionally absolute expiry time to a relative time. If an
716 * absolute time is specified which is in the past, use a short expiry time.
718 * @param int $exptime
721 protected function convertToRelative( $exptime ) {
722 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
723 $exptime -= (int)$this->getCurrentTime();
724 if ( $exptime <= 0 ) {
734 * Check if a value is an integer
736 * @param mixed $value
739 protected function isInteger( $value ) {
740 return ( is_int( $value ) ||
ctype_digit( $value ) );
744 * Construct a cache key.
747 * @param string $keyspace
749 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
751 public function makeKeyInternal( $keyspace, $args ) {
753 foreach ( $args as $arg ) {
754 $arg = str_replace( ':', '%3A', $arg );
755 $key = $key . ':' . $arg;
757 return strtr( $key, ' ', '_' );
761 * Make a global cache key.
764 * @param string $class Key class
765 * @param string $component [optional] Key component (starting with a key collection name)
766 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
768 public function makeGlobalKey( $class, $component = null ) {
769 return $this->makeKeyInternal( 'global', func_get_args() );
773 * Make a cache key, scoped to this instance's keyspace.
776 * @param string $class Key class
777 * @param string $component [optional] Key component (starting with a key collection name)
778 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
780 public function makeKey( $class, $component = null ) {
781 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
785 * @param int $flag ATTR_* class constant
786 * @return int QOS_* class constant
789 public function getQoS( $flag ) {
790 return isset( $this->attrMap
[$flag] ) ?
$this->attrMap
[$flag] : self
::QOS_UNKNOWN
;
794 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
796 * @param BagOStuff[] $bags
797 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
799 protected function mergeFlagMaps( array $bags ) {
801 foreach ( $bags as $bag ) {
802 foreach ( $bag->attrMap
as $attr => $rank ) {
803 if ( isset( $map[$attr] ) ) {
804 $map[$attr] = min( $map[$attr], $rank );
815 * @return float UNIX timestamp
816 * @codeCoverageIgnore
818 protected function getCurrentTime() {
819 return $this->wallClockOverride ?
: microtime( true );
823 * @param float|null &$time Mock UNIX timestamp for testing
824 * @codeCoverageIgnore
826 public function setMockTime( &$time ) {
827 $this->wallClockOverride
=& $time;