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 * interface is intended to be more or less compatible with
37 * the PHP memcached client.
39 * backends for local hash array and SQL table included:
41 * $bag = new HashBagOStuff();
42 * $bag = new SqlBagOStuff(); # connect to db first
47 abstract class BagOStuff
implements IExpiringStore
, LoggerAwareInterface
{
48 /** @var array[] Lock tracking */
49 protected $locks = [];
50 /** @var int ERR_* class constant */
51 protected $lastError = self
::ERR_NONE
;
53 protected $keyspace = 'local';
54 /** @var LoggerInterface */
56 /** @var callback|null */
57 protected $asyncHandler;
58 /** @var int Seconds */
59 protected $syncTimeout;
62 private $debugMode = false;
64 private $duplicateKeyLookups = [];
66 private $reportDupes = false;
68 private $dupeTrackScheduled = false;
70 /** @var callable[] */
71 protected $busyCallbacks = [];
73 /** @var float|null */
74 private $wallClockOverride;
76 /** @var int[] Map of (ATTR_* class constant => QOS_* class constant) */
77 protected $attrMap = [];
79 /** Possible values for getLastError() */
80 const ERR_NONE
= 0; // no error
81 const ERR_NO_RESPONSE
= 1; // no response
82 const ERR_UNREACHABLE
= 2; // can't connect
83 const ERR_UNEXPECTED
= 3; // response gave some error
85 /** Bitfield constants for get()/getMulti() */
86 const READ_LATEST
= 1; // use latest data for replicated stores
87 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
88 /** Bitfield constants for set()/merge() */
89 const WRITE_SYNC
= 1; // synchronously write to all locations for replicated stores
90 const WRITE_CACHE_ONLY
= 2; // Only change state of the in-memory cache
94 * - logger: Psr\Log\LoggerInterface instance
95 * - keyspace: Default keyspace for $this->makeKey()
96 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
97 * In CLI mode, it should run the task immediately.
98 * - reportDupes: Whether to emit warning log messages for all keys that were
99 * requested more than once (requires an asyncHandler).
100 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
101 * @param array $params
103 public function __construct( array $params = [] ) {
104 if ( isset( $params['logger'] ) ) {
105 $this->setLogger( $params['logger'] );
107 $this->setLogger( new NullLogger() );
110 if ( isset( $params['keyspace'] ) ) {
111 $this->keyspace
= $params['keyspace'];
114 $this->asyncHandler
= isset( $params['asyncHandler'] )
115 ?
$params['asyncHandler']
118 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
119 $this->reportDupes
= true;
122 $this->syncTimeout
= isset( $params['syncTimeout'] ) ?
$params['syncTimeout'] : 3;
126 * @param LoggerInterface $logger
129 public function setLogger( LoggerInterface
$logger ) {
130 $this->logger
= $logger;
136 public function setDebug( $bool ) {
137 $this->debugMode
= $bool;
141 * Get an item with the given key, regenerating and setting it if not found
143 * If the callback returns false, then nothing is stored.
146 * @param int $ttl Time-to-live (seconds)
147 * @param callable $callback Callback that derives the new value
148 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
149 * @return mixed The cached value if found or the result of $callback otherwise
152 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
153 $value = $this->get( $key, $flags );
155 if ( $value === false ) {
156 if ( !is_callable( $callback ) ) {
157 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
159 $value = call_user_func( $callback );
160 if ( $value !== false ) {
161 $this->set( $key, $value, $ttl );
169 * Get an item with the given key
171 * If the key includes a determistic input hash (e.g. the key can only have
172 * the correct value) or complete staleness checks are handled by the caller
173 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
174 * This lets tiered backends know they can safely upgrade a cached value to
175 * higher tiers using standard TTLs.
178 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
179 * @param int $oldFlags [unused]
180 * @return mixed Returns false on failure and if the item does not exist
182 public function get( $key, $flags = 0, $oldFlags = null ) {
183 // B/C for ( $key, &$casToken = null, $flags = 0 )
184 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
186 $this->trackDuplicateKeys( $key );
188 return $this->doGet( $key, $flags );
192 * Track the number of times that a given key has been used.
195 private function trackDuplicateKeys( $key ) {
196 if ( !$this->reportDupes
) {
200 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
201 // Track that we have seen this key. This N-1 counting style allows
202 // easy filtering with array_filter() later.
203 $this->duplicateKeyLookups
[$key] = 0;
205 $this->duplicateKeyLookups
[$key] +
= 1;
207 if ( $this->dupeTrackScheduled
=== false ) {
208 $this->dupeTrackScheduled
= true;
209 // Schedule a callback that logs keys processed more than once by get().
210 call_user_func( $this->asyncHandler
, function () {
211 $dups = array_filter( $this->duplicateKeyLookups
);
212 foreach ( $dups as $key => $count ) {
213 $this->logger
->warning(
214 'Duplicate get(): "{key}" fetched {count} times',
215 // Count is N-1 of the actual lookup count
216 [ 'key' => $key, 'count' => $count +
1, ]
226 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
227 * @return mixed Returns false on failure and if the item does not exist
229 abstract protected function doGet( $key, $flags = 0 );
232 * @note: This method is only needed if merge() uses mergeViaCas()
235 * @param mixed &$casToken
236 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
237 * @return mixed Returns false on failure and if the item does not exist
240 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
241 throw new Exception( __METHOD__
. ' not implemented.' );
248 * @param mixed $value
249 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
250 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
251 * @return bool Success
253 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
259 * @return bool True if the item was deleted or not found, false on failure
261 abstract public function delete( $key );
264 * Merge changes into the existing cache value (possibly creating a new one)
266 * The callback function returns the new value given the current value
267 * (which will be false if not present), and takes the arguments:
268 * (this BagOStuff, cache key, current value, TTL).
269 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
272 * @param callable $callback Callback method to be executed
273 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
274 * @param int $attempts The amount of times to attempt a merge in case of failure
275 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
276 * @return bool Success
277 * @throws InvalidArgumentException
279 public function merge( $key, callable
$callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
280 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
284 * @see BagOStuff::merge()
287 * @param callable $callback Callback method to be executed
288 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
289 * @param int $attempts The amount of times to attempt a merge in case of failure
290 * @return bool Success
292 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
294 $this->clearLastError();
295 $reportDupes = $this->reportDupes
;
296 $this->reportDupes
= false;
297 $casToken = null; // passed by reference
298 $currentValue = $this->getWithToken( $key, $casToken, self
::READ_LATEST
);
299 $this->reportDupes
= $reportDupes;
301 if ( $this->getLastError() ) {
302 return false; // don't spam retries (retry only on races)
305 // Derive the new value from the old value
306 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
308 $this->clearLastError();
309 if ( $value === false ) {
310 $success = true; // do nothing
311 } elseif ( $currentValue === false ) {
312 // Try to create the key, failing if it gets created in the meantime
313 $success = $this->add( $key, $value, $exptime );
315 // Try to update the key, failing if it gets changed in the meantime
316 $success = $this->cas( $casToken, $key, $value, $exptime );
318 if ( $this->getLastError() ) {
319 return false; // IO error; don't spam retries
321 } while ( !$success && --$attempts );
327 * Check and set an item
329 * @param mixed $casToken
331 * @param mixed $value
332 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
333 * @return bool Success
336 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
337 throw new Exception( "CAS is not implemented in " . __CLASS__
);
341 * @see BagOStuff::merge()
344 * @param callable $callback Callback method to be executed
345 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
346 * @param int $attempts The amount of times to attempt a merge in case of failure
347 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
348 * @return bool Success
350 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
351 if ( !$this->lock( $key, 6 ) ) {
355 $this->clearLastError();
356 $reportDupes = $this->reportDupes
;
357 $this->reportDupes
= false;
358 $currentValue = $this->get( $key, self
::READ_LATEST
);
359 $this->reportDupes
= $reportDupes;
361 if ( $this->getLastError() ) {
364 // Derive the new value from the old value
365 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
366 if ( $value === false ) {
367 $success = true; // do nothing
369 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
373 if ( !$this->unlock( $key ) ) {
374 // this should never happen
375 trigger_error( "Could not release lock for key '$key'." );
382 * Reset the TTL on a key if it exists
386 * @return bool Success Returns false if there is no key
389 public function changeTTL( $key, $expiry = 0 ) {
390 $value = $this->get( $key );
392 return ( $value === false ) ?
false : $this->set( $key, $value, $expiry );
396 * Acquire an advisory lock on a key string
398 * Note that if reentry is enabled, duplicate calls ignore $expiry
401 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
402 * @param int $expiry Lock expiry [optional]; 1 day maximum
403 * @param string $rclass Allow reentry if set and the current lock used this value
404 * @return bool Success
406 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
407 // Avoid deadlocks and allow lock reentry if specified
408 if ( isset( $this->locks
[$key] ) ) {
409 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
410 ++
$this->locks
[$key]['depth'];
417 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
418 $loop = new WaitConditionLoop(
419 function () use ( $key, $timeout, $expiry ) {
420 $this->clearLastError();
421 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
422 return true; // locked!
423 } elseif ( $this->getLastError() ) {
424 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
427 return WaitConditionLoop
::CONDITION_CONTINUE
;
432 $locked = ( $loop->invoke() === $loop::CONDITION_REACHED
);
434 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
441 * Release an advisory lock on a key string
444 * @return bool Success
446 public function unlock( $key ) {
447 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
448 unset( $this->locks
[$key] );
450 return $this->delete( "{$key}:lock" );
457 * Get a lightweight exclusive self-unlocking lock
459 * Note that the same lock cannot be acquired twice.
461 * This is useful for task de-duplication or to avoid obtrusive
462 * (though non-corrupting) DB errors like INSERT key conflicts
463 * or deadlocks when using LOCK IN SHARE MODE.
466 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
467 * @param int $expiry Lock expiry [optional]; 1 day maximum
468 * @param string $rclass Allow reentry if set and the current lock used this value
469 * @return ScopedCallback|null Returns null on failure
472 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
473 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
475 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
479 $lSince = $this->getCurrentTime(); // lock timestamp
481 return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
482 $latency = 0.050; // latency skew (err towards keeping lock present)
483 $age = ( $this->getCurrentTime() - $lSince +
$latency );
484 if ( ( $age +
$latency ) >= $expiry ) {
485 $this->logger
->warning( "Lock for $key held too long ($age sec)." );
486 return; // expired; it's not "safe" to delete the key
488 $this->unlock( $key );
493 * Delete all objects expiring before a certain date.
494 * @param string $date The reference date in MW format
495 * @param callable|bool $progressCallback Optional, a function which will be called
496 * regularly during long-running operations with the percentage progress
497 * as the first parameter.
499 * @return bool Success, false if unimplemented
501 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
507 * Get an associative array containing the item for each of the keys that have items.
508 * @param array $keys List of strings
509 * @param int $flags Bitfield; supports READ_LATEST [optional]
512 public function getMulti( array $keys, $flags = 0 ) {
514 foreach ( $keys as $key ) {
515 $val = $this->get( $key );
516 if ( $val !== false ) {
525 * @param array $data $key => $value assoc array
526 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
527 * @return bool Success
530 public function setMulti( array $data, $exptime = 0 ) {
532 foreach ( $data as $key => $value ) {
533 if ( !$this->set( $key, $value, $exptime ) ) {
542 * @param mixed $value
543 * @param int $exptime
544 * @return bool Success
546 public function add( $key, $value, $exptime = 0 ) {
547 if ( $this->get( $key ) === false ) {
548 return $this->set( $key, $value, $exptime );
550 return false; // key already set
554 * Increase stored value of $key by $value while preserving its TTL
555 * @param string $key Key to increase
556 * @param int $value Value to add to $key (Default 1)
557 * @return int|bool New value or false on failure
559 public function incr( $key, $value = 1 ) {
560 if ( !$this->lock( $key ) ) {
563 $n = $this->get( $key );
564 if ( $this->isInteger( $n ) ) { // key exists?
565 $n +
= intval( $value );
566 $this->set( $key, max( 0, $n ) ); // exptime?
570 $this->unlock( $key );
576 * Decrease stored value of $key by $value while preserving its TTL
579 * @return int|bool New value or false on failure
581 public function decr( $key, $value = 1 ) {
582 return $this->incr( $key, - $value );
586 * Increase stored value of $key by $value while preserving its TTL
588 * This will create the key with value $init and TTL $ttl instead if not present
594 * @return int|bool New value or false on failure
597 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
598 $newValue = $this->incr( $key, $value );
599 if ( $newValue === false ) {
600 // No key set; initialize
601 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
603 if ( $newValue === false ) {
604 // Raced out initializing; increment
605 $newValue = $this->incr( $key, $value );
612 * Get the "last error" registered; clearLastError() should be called manually
613 * @return int ERR_* constant for the "last error" registry
616 public function getLastError() {
617 return $this->lastError
;
621 * Clear the "last error" registry
624 public function clearLastError() {
625 $this->lastError
= self
::ERR_NONE
;
629 * Set the "last error" registry
630 * @param int $err ERR_* constant
633 protected function setLastError( $err ) {
634 $this->lastError
= $err;
638 * Let a callback be run to avoid wasting time on special blocking calls
640 * The callbacks may or may not be called ever, in any particular order.
641 * They are likely to be invoked when something WRITE_SYNC is used used.
642 * They should follow a caching pattern as shown below, so that any code
643 * using the word will get it's result no matter what happens.
646 * $workCallback = function () use ( &$result ) {
654 * @param callable $workCallback
657 public function addBusyCallback( callable
$workCallback ) {
658 $this->busyCallbacks
[] = $workCallback;
662 * Modify a cache update operation array for EventRelayer::notify()
664 * This is used for relayed writes, e.g. for broadcasting a change
665 * to multiple data-centers. If the array contains a 'val' field
666 * then the command involves setting a key to that value. Note that
667 * for simplicity, 'val' is always a simple scalar value. This method
668 * is used to possibly serialize the value and add any cache-specific
669 * key/values needed for the relayer daemon (e.g. memcached flags).
671 * @param array $event
675 public function modifySimpleRelayEvent( array $event ) {
680 * @param string $text
682 protected function debug( $text ) {
683 if ( $this->debugMode
) {
684 $this->logger
->debug( "{class} debug: $text", [
685 'class' => static::class,
691 * Convert an optionally relative time to an absolute time
692 * @param int $exptime
695 protected function convertExpiry( $exptime ) {
696 if ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) ) {
697 return (int)$this->getCurrentTime() +
$exptime;
704 * Convert an optionally absolute expiry time to a relative time. If an
705 * absolute time is specified which is in the past, use a short expiry time.
707 * @param int $exptime
710 protected function convertToRelative( $exptime ) {
711 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
712 $exptime -= (int)$this->getCurrentTime();
713 if ( $exptime <= 0 ) {
723 * Check if a value is an integer
725 * @param mixed $value
728 protected function isInteger( $value ) {
729 return ( is_int( $value ) ||
ctype_digit( $value ) );
733 * Construct a cache key.
736 * @param string $keyspace
738 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
740 public function makeKeyInternal( $keyspace, $args ) {
742 foreach ( $args as $arg ) {
743 $arg = str_replace( ':', '%3A', $arg );
744 $key = $key . ':' . $arg;
746 return strtr( $key, ' ', '_' );
750 * Make a global cache key.
753 * @param string $class Key class
754 * @param string $component [optional] Key component (starting with a key collection name)
755 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
757 public function makeGlobalKey( $class, $component = null ) {
758 return $this->makeKeyInternal( 'global', func_get_args() );
762 * Make a cache key, scoped to this instance's keyspace.
765 * @param string $class Key class
766 * @param string $component [optional] Key component (starting with a key collection name)
767 * @return string Colon-delimited list of $keyspace followed by escaped components of $args
769 public function makeKey( $class, $component = null ) {
770 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
774 * @param int $flag ATTR_* class constant
775 * @return int QOS_* class constant
778 public function getQoS( $flag ) {
779 return isset( $this->attrMap
[$flag] ) ?
$this->attrMap
[$flag] : self
::QOS_UNKNOWN
;
783 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
785 * @param BagOStuff[] $bags
786 * @return int[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
788 protected function mergeFlagMaps( array $bags ) {
790 foreach ( $bags as $bag ) {
791 foreach ( $bag->attrMap
as $attr => $rank ) {
792 if ( isset( $map[$attr] ) ) {
793 $map[$attr] = min( $map[$attr], $rank );
804 * @return float UNIX timestamp
805 * @codeCoverageIgnore
807 protected function getCurrentTime() {
808 return $this->wallClockOverride ?
: microtime( true );
812 * @param float|null &$time Mock UNIX timestamp for testing
813 * @codeCoverageIgnore
815 public function setMockTime( &$time ) {
816 $this->wallClockOverride
=& $time;