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 /** 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 $this->setLogger( $params['logger'] ??
new NullLogger() );
117 if ( isset( $params['keyspace'] ) ) {
118 $this->keyspace
= $params['keyspace'];
121 $this->asyncHandler
= $params['asyncHandler'] ??
null;
123 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
124 $this->reportDupes
= true;
127 $this->syncTimeout
= $params['syncTimeout'] ??
3;
131 * @param LoggerInterface $logger
134 public function setLogger( LoggerInterface
$logger ) {
135 $this->logger
= $logger;
141 public function setDebug( $bool ) {
142 $this->debugMode
= $bool;
146 * Get an item with the given key, regenerating and setting it if not found
148 * If the callback returns false, then nothing is stored.
151 * @param int $ttl Time-to-live (seconds)
152 * @param callable $callback Callback that derives the new value
153 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
154 * @return mixed The cached value if found or the result of $callback otherwise
157 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
158 $value = $this->get( $key, $flags );
160 if ( $value === false ) {
161 if ( !is_callable( $callback ) ) {
162 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
164 $value = call_user_func( $callback );
165 if ( $value !== false ) {
166 $this->set( $key, $value, $ttl );
174 * Get an item with the given key
176 * If the key includes a deterministic input hash (e.g. the key can only have
177 * the correct value) or complete staleness checks are handled by the caller
178 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
179 * This lets tiered backends know they can safely upgrade a cached value to
180 * higher tiers using standard TTLs.
183 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
184 * @param int|null $oldFlags [unused]
185 * @return mixed Returns false on failure and if the item does not exist
187 public function get( $key, $flags = 0, $oldFlags = null ) {
188 // B/C for ( $key, &$casToken = null, $flags = 0 )
189 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
191 $this->trackDuplicateKeys( $key );
193 return $this->doGet( $key, $flags );
197 * Track the number of times that a given key has been used.
200 private function trackDuplicateKeys( $key ) {
201 if ( !$this->reportDupes
) {
205 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
206 // Track that we have seen this key. This N-1 counting style allows
207 // easy filtering with array_filter() later.
208 $this->duplicateKeyLookups
[$key] = 0;
210 $this->duplicateKeyLookups
[$key] +
= 1;
212 if ( $this->dupeTrackScheduled
=== false ) {
213 $this->dupeTrackScheduled
= true;
214 // Schedule a callback that logs keys processed more than once by get().
215 call_user_func( $this->asyncHandler
, function () {
216 $dups = array_filter( $this->duplicateKeyLookups
);
217 foreach ( $dups as $key => $count ) {
218 $this->logger
->warning(
219 'Duplicate get(): "{key}" fetched {count} times',
220 // Count is N-1 of the actual lookup count
221 [ 'key' => $key, 'count' => $count +
1, ]
231 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
232 * @return mixed Returns false on failure and if the item does not exist
234 abstract protected function doGet( $key, $flags = 0 );
237 * @note This method is only needed if merge() uses mergeViaCas()
240 * @param mixed &$casToken
241 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
242 * @return mixed Returns false on failure and if the item does not exist
245 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
246 throw new Exception( __METHOD__
. ' not implemented.' );
253 * @param mixed $value
254 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
255 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
256 * @return bool Success
258 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
264 * @return bool True if the item was deleted or not found, false on failure
265 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
267 abstract public function delete( $key, $flags = 0 );
270 * Merge changes into the existing cache value (possibly creating a new one)
272 * The callback function returns the new value given the current value
273 * (which will be false if not present), and takes the arguments:
274 * (this BagOStuff, cache key, current value, TTL).
275 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
278 * @param callable $callback Callback method to be executed
279 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
280 * @param int $attempts The amount of times to attempt a merge in case of failure
281 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
282 * @return bool Success
283 * @throws InvalidArgumentException
285 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
286 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
290 * @see BagOStuff::merge()
293 * @param callable $callback Callback method to be executed
294 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
295 * @param int $attempts The amount of times to attempt a merge in case of failure
296 * @return bool Success
298 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
300 $this->clearLastError();
301 $reportDupes = $this->reportDupes
;
302 $this->reportDupes
= false;
303 $casToken = null; // passed by reference
304 $currentValue = $this->getWithToken( $key, $casToken, self
::READ_LATEST
);
305 $this->reportDupes
= $reportDupes;
307 if ( $this->getLastError() ) {
308 $this->logger
->warning(
309 __METHOD__
. ' failed due to I/O error on get() for {key}.',
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 $this->logger
->warning(
331 __METHOD__
. ' failed due to I/O error for {key}.',
335 return false; // IO error; don't spam retries
337 } while ( !$success && --$attempts );
343 * Check and set an item
345 * @param mixed $casToken
347 * @param mixed $value
348 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
349 * @return bool Success
352 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
353 if ( !$this->lock( $key, 0 ) ) {
354 return false; // non-blocking
357 $curCasToken = null; // passed by reference
358 $this->getWithToken( $key, $curCasToken, self
::READ_LATEST
);
359 if ( $casToken === $curCasToken ) {
360 $success = $this->set( $key, $value, $exptime );
363 __METHOD__
. ' failed due to race condition for {key}.',
367 $success = false; // mismatched or failed
370 $this->unlock( $key );
376 * @see BagOStuff::merge()
379 * @param callable $callback Callback method to be executed
380 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
381 * @param int $attempts The amount of times to attempt a merge in case of failure
382 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
383 * @return bool Success
385 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
386 if ( $attempts <= 1 ) {
387 $timeout = 0; // clearly intended to be "non-blocking"
392 if ( !$this->lock( $key, $timeout ) ) {
396 $this->clearLastError();
397 $reportDupes = $this->reportDupes
;
398 $this->reportDupes
= false;
399 $currentValue = $this->get( $key, self
::READ_LATEST
);
400 $this->reportDupes
= $reportDupes;
402 if ( $this->getLastError() ) {
403 $this->logger
->warning(
404 __METHOD__
. ' failed due to I/O error on get() for {key}.',
410 // Derive the new value from the old value
411 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
412 if ( $value === false ) {
413 $success = true; // do nothing
415 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
419 if ( !$this->unlock( $key ) ) {
420 // this should never happen
421 trigger_error( "Could not release lock for key '$key'." );
428 * Reset the TTL on a key if it exists
432 * @return bool Success Returns false if there is no key
435 public function changeTTL( $key, $expiry = 0 ) {
436 $value = $this->get( $key );
438 return ( $value === false ) ?
false : $this->set( $key, $value, $expiry );
442 * Acquire an advisory lock on a key string
444 * Note that if reentry is enabled, duplicate calls ignore $expiry
447 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
448 * @param int $expiry Lock expiry [optional]; 1 day maximum
449 * @param string $rclass Allow reentry if set and the current lock used this value
450 * @return bool Success
452 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
453 // Avoid deadlocks and allow lock reentry if specified
454 if ( isset( $this->locks
[$key] ) ) {
455 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
456 ++
$this->locks
[$key]['depth'];
464 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
465 $loop = new WaitConditionLoop(
466 function () use ( $key, $expiry, $fname ) {
467 $this->clearLastError();
468 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
469 return true; // locked!
470 } elseif ( $this->getLastError() ) {
471 $this->logger
->warning(
472 $fname . ' failed due to I/O error for {key}.',
476 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
479 return WaitConditionLoop
::CONDITION_CONTINUE
;
484 $code = $loop->invoke();
485 $locked = ( $code === $loop::CONDITION_REACHED
);
487 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
488 } elseif ( $code === $loop::CONDITION_TIMED_OUT
) {
489 $this->logger
->warning(
490 "$fname failed due to timeout for {key}.",
491 [ 'key' => $key, 'timeout' => $timeout ]
499 * Release an advisory lock on a key string
502 * @return bool Success
504 public function unlock( $key ) {
505 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
506 unset( $this->locks
[$key] );
508 $ok = $this->delete( "{$key}:lock" );
510 $this->logger
->warning(
511 __METHOD__
. ' failed to release lock for {key}.',
523 * Get a lightweight exclusive self-unlocking lock
525 * Note that the same lock cannot be acquired twice.
527 * This is useful for task de-duplication or to avoid obtrusive
528 * (though non-corrupting) DB errors like INSERT key conflicts
529 * or deadlocks when using LOCK IN SHARE MODE.
532 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
533 * @param int $expiry Lock expiry [optional]; 1 day maximum
534 * @param string $rclass Allow reentry if set and the current lock used this value
535 * @return ScopedCallback|null Returns null on failure
538 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
539 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
541 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
545 $lSince = $this->getCurrentTime(); // lock timestamp
547 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
548 $latency = 0.050; // latency skew (err towards keeping lock present)
549 $age = ( $this->getCurrentTime() - $lSince +
$latency );
550 if ( ( $age +
$latency ) >= $expiry ) {
551 $this->logger
->warning(
552 "Lock for {key} held too long ({age} sec).",
553 [ 'key' => $key, 'age' => $age ]
555 return; // expired; it's not "safe" to delete the key
557 $this->unlock( $key );
562 * Delete all objects expiring before a certain date.
563 * @param string $date The reference date in MW format
564 * @param callable|bool $progressCallback Optional, a function which will be called
565 * regularly during long-running operations with the percentage progress
566 * as the first parameter.
568 * @return bool Success, false if unimplemented
570 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
576 * Get an associative array containing the item for each of the keys that have items.
577 * @param array $keys List of strings
578 * @param int $flags Bitfield; supports READ_LATEST [optional]
581 public function getMulti( array $keys, $flags = 0 ) {
583 foreach ( $keys as $key ) {
584 $val = $this->get( $key );
585 if ( $val !== false ) {
594 * @param array $data $key => $value assoc array
595 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
596 * @return bool Success
599 public function setMulti( array $data, $exptime = 0 ) {
601 foreach ( $data as $key => $value ) {
602 if ( !$this->set( $key, $value, $exptime ) ) {
611 * @param mixed $value
612 * @param int $exptime
613 * @return bool Success
615 public function add( $key, $value, $exptime = 0 ) {
616 // @note: avoid lock() here since that method uses *this* method by default
617 if ( $this->get( $key ) === false ) {
618 return $this->set( $key, $value, $exptime );
620 return false; // key already set
624 * Increase stored value of $key by $value while preserving its TTL
625 * @param string $key Key to increase
626 * @param int $value Value to add to $key (Default 1)
627 * @return int|bool New value or false on failure
629 public function incr( $key, $value = 1 ) {
630 if ( !$this->lock( $key, 1 ) ) {
633 $n = $this->get( $key );
634 if ( $this->isInteger( $n ) ) { // key exists?
635 $n +
= intval( $value );
636 $this->set( $key, max( 0, $n ) ); // exptime?
640 $this->unlock( $key );
646 * Decrease stored value of $key by $value while preserving its TTL
649 * @return int|bool New value or false on failure
651 public function decr( $key, $value = 1 ) {
652 return $this->incr( $key, - $value );
656 * Increase stored value of $key by $value while preserving its TTL
658 * This will create the key with value $init and TTL $ttl instead if not present
664 * @return int|bool New value or false on failure
667 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
668 $this->clearLastError();
669 $newValue = $this->incr( $key, $value );
670 if ( $newValue === false && !$this->getLastError() ) {
671 // No key set; initialize
672 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
673 if ( $newValue === false && !$this->getLastError() ) {
674 // Raced out initializing; increment
675 $newValue = $this->incr( $key, $value );
683 * Get the "last error" registered; clearLastError() should be called manually
684 * @return int ERR_* constant for the "last error" registry
687 public function getLastError() {
688 return $this->lastError
;
692 * Clear the "last error" registry
695 public function clearLastError() {
696 $this->lastError
= self
::ERR_NONE
;
700 * Set the "last error" registry
701 * @param int $err ERR_* constant
704 protected function setLastError( $err ) {
705 $this->lastError
= $err;
709 * Let a callback be run to avoid wasting time on special blocking calls
711 * The callbacks may or may not be called ever, in any particular order.
712 * They are likely to be invoked when something WRITE_SYNC is used used.
713 * They should follow a caching pattern as shown below, so that any code
714 * using the work will get it's result no matter what happens.
717 * $workCallback = function () use ( &$result ) {
725 * @param callable $workCallback
728 public function addBusyCallback( callable
$workCallback ) {
729 $this->busyCallbacks
[] = $workCallback;
733 * @param string $text
735 protected function debug( $text ) {
736 if ( $this->debugMode
) {
737 $this->logger
->debug( "{class} debug: $text", [
738 'class' => static::class,
744 * Convert an optionally relative time to an absolute time
745 * @param int $exptime
748 protected function convertExpiry( $exptime ) {
749 if ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) ) {
750 return (int)$this->getCurrentTime() +
$exptime;
757 * Convert an optionally absolute expiry time to a relative time. If an
758 * absolute time is specified which is in the past, use a short expiry time.
760 * @param int $exptime
763 protected function convertToRelative( $exptime ) {
764 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
765 $exptime -= (int)$this->getCurrentTime();
766 if ( $exptime <= 0 ) {
776 * Check if a value is an integer
778 * @param mixed $value
781 protected function isInteger( $value ) {
782 return ( is_int( $value ) ||
ctype_digit( $value ) );
786 * Construct a cache key.
789 * @param string $keyspace
791 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
793 public function makeKeyInternal( $keyspace, $args ) {
795 foreach ( $args as $arg ) {
796 $arg = str_replace( ':', '%3A', $arg );
799 return strtr( $key, ' ', '_' );
803 * Make a global cache key.
806 * @param string $class Key class
807 * @param string|null $component [optional] Key component (starting with a key collection name)
808 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
810 public function makeGlobalKey( $class, $component = null ) {
811 return $this->makeKeyInternal( 'global', func_get_args() );
815 * Make a cache key, scoped to this instance's keyspace.
818 * @param string $class Key class
819 * @param string|null $component [optional] Key component (starting with a key collection name)
820 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
822 public function makeKey( $class, $component = null ) {
823 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
827 * @param int $flag ATTR_* class constant
828 * @return int QOS_* class constant
831 public function getQoS( $flag ) {
832 return $this->attrMap
[$flag] ?? self
::QOS_UNKNOWN
;
836 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
838 * @param BagOStuff[] $bags
839 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
841 protected function mergeFlagMaps( array $bags ) {
843 foreach ( $bags as $bag ) {
844 foreach ( $bag->attrMap
as $attr => $rank ) {
845 if ( isset( $map[$attr] ) ) {
846 $map[$attr] = min( $map[$attr], $rank );
857 * @return float UNIX timestamp
858 * @codeCoverageIgnore
860 protected function getCurrentTime() {
861 return $this->wallClockOverride ?
: microtime( true );
865 * @param float|null &$time Mock UNIX timestamp for testing
866 * @codeCoverageIgnore
868 public function setMockTime( &$time ) {
869 $this->wallClockOverride
=& $time;