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\WaitConditionLoop
;
35 * interface is intended to be more or less compatible with
36 * the PHP memcached client.
38 * backends for local hash array and SQL table included:
40 * $bag = new HashBagOStuff();
41 * $bag = new SqlBagOStuff(); # connect to db first
46 abstract class BagOStuff
implements IExpiringStore
, LoggerAwareInterface
{
47 /** @var array[] Lock tracking */
48 protected $locks = [];
49 /** @var integer ERR_* class constant */
50 protected $lastError = self
::ERR_NONE
;
52 protected $keyspace = 'local';
53 /** @var LoggerInterface */
55 /** @var callback|null */
56 protected $asyncHandler;
57 /** @var integer Seconds */
58 protected $syncTimeout;
61 private $debugMode = false;
63 private $duplicateKeyLookups = [];
65 private $reportDupes = false;
67 private $dupeTrackScheduled = false;
69 /** @var callable[] */
70 protected $busyCallbacks = [];
72 /** @var integer[] Map of (ATTR_* class constant => QOS_* class constant) */
73 protected $attrMap = [];
75 /** Possible values for getLastError() */
76 const ERR_NONE
= 0; // no error
77 const ERR_NO_RESPONSE
= 1; // no response
78 const ERR_UNREACHABLE
= 2; // can't connect
79 const ERR_UNEXPECTED
= 3; // response gave some error
81 /** Bitfield constants for get()/getMulti() */
82 const READ_LATEST
= 1; // use latest data for replicated stores
83 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
84 /** Bitfield constants for set()/merge() */
85 const WRITE_SYNC
= 1; // synchronously write to all locations for replicated stores
86 const WRITE_CACHE_ONLY
= 2; // Only change state of the in-memory cache
90 * - logger: Psr\Log\LoggerInterface instance
91 * - keyspace: Default keyspace for $this->makeKey()
92 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
93 * In CLI mode, it should run the task immediately.
94 * - reportDupes: Whether to emit warning log messages for all keys that were
95 * requested more than once (requires an asyncHandler).
96 * - syncTimeout: How long to wait with WRITE_SYNC in seconds.
97 * @param array $params
99 public function __construct( array $params = [] ) {
100 if ( isset( $params['logger'] ) ) {
101 $this->setLogger( $params['logger'] );
103 $this->setLogger( new NullLogger() );
106 if ( isset( $params['keyspace'] ) ) {
107 $this->keyspace
= $params['keyspace'];
110 $this->asyncHandler
= isset( $params['asyncHandler'] )
111 ?
$params['asyncHandler']
114 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
115 $this->reportDupes
= true;
118 $this->syncTimeout
= isset( $params['syncTimeout'] ) ?
$params['syncTimeout'] : 3;
122 * @param LoggerInterface $logger
125 public function setLogger( LoggerInterface
$logger ) {
126 $this->logger
= $logger;
132 public function setDebug( $bool ) {
133 $this->debugMode
= $bool;
137 * Get an item with the given key, regenerating and setting it if not found
139 * If the callback returns false, then nothing is stored.
142 * @param int $ttl Time-to-live (seconds)
143 * @param callable $callback Callback that derives the new value
144 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
145 * @return mixed The cached value if found or the result of $callback otherwise
148 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
149 $value = $this->get( $key, $flags );
151 if ( $value === false ) {
152 if ( !is_callable( $callback ) ) {
153 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
155 $value = call_user_func( $callback );
156 if ( $value !== false ) {
157 $this->set( $key, $value, $ttl );
165 * Get an item with the given key
167 * If the key includes a determistic input hash (e.g. the key can only have
168 * the correct value) or complete staleness checks are handled by the caller
169 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
170 * This lets tiered backends know they can safely upgrade a cached value to
171 * higher tiers using standard TTLs.
174 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
175 * @param integer $oldFlags [unused]
176 * @return mixed Returns false on failure and if the item does not exist
178 public function get( $key, $flags = 0, $oldFlags = null ) {
179 // B/C for ( $key, &$casToken = null, $flags = 0 )
180 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
182 $this->trackDuplicateKeys( $key );
184 return $this->doGet( $key, $flags );
188 * Track the number of times that a given key has been used.
191 private function trackDuplicateKeys( $key ) {
192 if ( !$this->reportDupes
) {
196 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
197 // Track that we have seen this key. This N-1 counting style allows
198 // easy filtering with array_filter() later.
199 $this->duplicateKeyLookups
[$key] = 0;
201 $this->duplicateKeyLookups
[$key] +
= 1;
203 if ( $this->dupeTrackScheduled
=== false ) {
204 $this->dupeTrackScheduled
= true;
205 // Schedule a callback that logs keys processed more than once by get().
206 call_user_func( $this->asyncHandler
, function () {
207 $dups = array_filter( $this->duplicateKeyLookups
);
208 foreach ( $dups as $key => $count ) {
209 $this->logger
->warning(
210 'Duplicate get(): "{key}" fetched {count} times',
211 // Count is N-1 of the actual lookup count
212 [ 'key' => $key, 'count' => $count +
1, ]
222 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
223 * @return mixed Returns false on failure and if the item does not exist
225 abstract protected function doGet( $key, $flags = 0 );
228 * @note: This method is only needed if merge() uses mergeViaCas()
231 * @param mixed $casToken
232 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
233 * @return mixed Returns false on failure and if the item does not exist
236 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
237 throw new Exception( __METHOD__
. ' not implemented.' );
244 * @param mixed $value
245 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
246 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
247 * @return bool Success
249 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
255 * @return bool True if the item was deleted or not found, false on failure
257 abstract public function delete( $key );
260 * Merge changes into the existing cache value (possibly creating a new one)
262 * The callback function returns the new value given the current value
263 * (which will be false if not present), and takes the arguments:
264 * (this BagOStuff, cache key, current value, TTL).
265 * The TTL parameter is reference set to $exptime. It can be overriden in the callback.
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->mergeViaLock( $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 * @return bool Success
288 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
290 $this->clearLastError();
291 $reportDupes = $this->reportDupes
;
292 $this->reportDupes
= false;
293 $casToken = null; // passed by reference
294 $currentValue = $this->getWithToken( $key, $casToken, self
::READ_LATEST
);
295 $this->reportDupes
= $reportDupes;
297 if ( $this->getLastError() ) {
298 return false; // don't spam retries (retry only on races)
301 // Derive the new value from the old value
302 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
304 $this->clearLastError();
305 if ( $value === false ) {
306 $success = true; // do nothing
307 } elseif ( $currentValue === false ) {
308 // Try to create the key, failing if it gets created in the meantime
309 $success = $this->add( $key, $value, $exptime );
311 // Try to update the key, failing if it gets changed in the meantime
312 $success = $this->cas( $casToken, $key, $value, $exptime );
314 if ( $this->getLastError() ) {
315 return false; // IO error; don't spam retries
317 } while ( !$success && --$attempts );
323 * Check and set an item
325 * @param mixed $casToken
327 * @param mixed $value
328 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
329 * @return bool Success
332 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
333 throw new Exception( "CAS is not implemented in " . __CLASS__
);
337 * @see BagOStuff::merge()
340 * @param callable $callback Callback method to be executed
341 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
342 * @param int $attempts The amount of times to attempt a merge in case of failure
343 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
344 * @return bool Success
346 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
347 if ( !$this->lock( $key, 6 ) ) {
351 $this->clearLastError();
352 $reportDupes = $this->reportDupes
;
353 $this->reportDupes
= false;
354 $currentValue = $this->get( $key, self
::READ_LATEST
);
355 $this->reportDupes
= $reportDupes;
357 if ( $this->getLastError() ) {
360 // Derive the new value from the old value
361 $value = call_user_func( $callback, $this, $key, $currentValue, $exptime );
362 if ( $value === false ) {
363 $success = true; // do nothing
365 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
369 if ( !$this->unlock( $key ) ) {
370 // this should never happen
371 trigger_error( "Could not release lock for key '$key'." );
378 * Reset the TTL on a key if it exists
382 * @return bool Success Returns false if there is no key
385 public function changeTTL( $key, $expiry = 0 ) {
386 $value = $this->get( $key );
388 return ( $value === false ) ?
false : $this->set( $key, $value, $expiry );
392 * Acquire an advisory lock on a key string
394 * Note that if reentry is enabled, duplicate calls ignore $expiry
397 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
398 * @param int $expiry Lock expiry [optional]; 1 day maximum
399 * @param string $rclass Allow reentry if set and the current lock used this value
400 * @return bool Success
402 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
403 // Avoid deadlocks and allow lock reentry if specified
404 if ( isset( $this->locks
[$key] ) ) {
405 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
406 ++
$this->locks
[$key]['depth'];
413 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
414 $loop = new WaitConditionLoop(
415 function () use ( $key, $timeout, $expiry ) {
416 $this->clearLastError();
417 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
418 return true; // locked!
419 } elseif ( $this->getLastError() ) {
420 return WaitConditionLoop
::CONDITION_ABORTED
; // network partition?
423 return WaitConditionLoop
::CONDITION_CONTINUE
;
428 $locked = ( $loop->invoke() === $loop::CONDITION_REACHED
);
430 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
437 * Release an advisory lock on a key string
440 * @return bool Success
442 public function unlock( $key ) {
443 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
444 unset( $this->locks
[$key] );
446 return $this->delete( "{$key}:lock" );
453 * Get a lightweight exclusive self-unlocking lock
455 * Note that the same lock cannot be acquired twice.
457 * This is useful for task de-duplication or to avoid obtrusive
458 * (though non-corrupting) DB errors like INSERT key conflicts
459 * or deadlocks when using LOCK IN SHARE MODE.
462 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
463 * @param int $expiry Lock expiry [optional]; 1 day maximum
464 * @param string $rclass Allow reentry if set and the current lock used this value
465 * @return ScopedCallback|null Returns null on failure
468 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
469 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
471 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
475 $lSince = microtime( true ); // lock timestamp
477 return new ScopedCallback( function() use ( $key, $lSince, $expiry ) {
478 $latency = .050; // latency skew (err towards keeping lock present)
479 $age = ( microtime( true ) - $lSince +
$latency );
480 if ( ( $age +
$latency ) >= $expiry ) {
481 $this->logger
->warning( "Lock for $key held too long ($age sec)." );
482 return; // expired; it's not "safe" to delete the key
484 $this->unlock( $key );
489 * Delete all objects expiring before a certain date.
490 * @param string $date The reference date in MW format
491 * @param callable|bool $progressCallback Optional, a function which will be called
492 * regularly during long-running operations with the percentage progress
493 * as the first parameter.
495 * @return bool Success, false if unimplemented
497 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
503 * Get an associative array containing the item for each of the keys that have items.
504 * @param array $keys List of strings
505 * @param integer $flags Bitfield; supports READ_LATEST [optional]
508 public function getMulti( array $keys, $flags = 0 ) {
510 foreach ( $keys as $key ) {
511 $val = $this->get( $key );
512 if ( $val !== false ) {
521 * @param array $data $key => $value assoc array
522 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
523 * @return bool Success
526 public function setMulti( array $data, $exptime = 0 ) {
528 foreach ( $data as $key => $value ) {
529 if ( !$this->set( $key, $value, $exptime ) ) {
538 * @param mixed $value
539 * @param int $exptime
540 * @return bool Success
542 public function add( $key, $value, $exptime = 0 ) {
543 if ( $this->get( $key ) === false ) {
544 return $this->set( $key, $value, $exptime );
546 return false; // key already set
550 * Increase stored value of $key by $value while preserving its TTL
551 * @param string $key Key to increase
552 * @param int $value Value to add to $key (Default 1)
553 * @return int|bool New value or false on failure
555 public function incr( $key, $value = 1 ) {
556 if ( !$this->lock( $key ) ) {
559 $n = $this->get( $key );
560 if ( $this->isInteger( $n ) ) { // key exists?
561 $n +
= intval( $value );
562 $this->set( $key, max( 0, $n ) ); // exptime?
566 $this->unlock( $key );
572 * Decrease stored value of $key by $value while preserving its TTL
575 * @return int|bool New value or false on failure
577 public function decr( $key, $value = 1 ) {
578 return $this->incr( $key, - $value );
582 * Increase stored value of $key by $value while preserving its TTL
584 * This will create the key with value $init and TTL $ttl instead if not present
590 * @return int|bool New value or false on failure
593 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
594 $newValue = $this->incr( $key, $value );
595 if ( $newValue === false ) {
596 // No key set; initialize
597 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
599 if ( $newValue === false ) {
600 // Raced out initializing; increment
601 $newValue = $this->incr( $key, $value );
608 * Get the "last error" registered; clearLastError() should be called manually
609 * @return int ERR_* constant for the "last error" registry
612 public function getLastError() {
613 return $this->lastError
;
617 * Clear the "last error" registry
620 public function clearLastError() {
621 $this->lastError
= self
::ERR_NONE
;
625 * Set the "last error" registry
626 * @param int $err ERR_* constant
629 protected function setLastError( $err ) {
630 $this->lastError
= $err;
634 * Let a callback be run to avoid wasting time on special blocking calls
636 * The callbacks may or may not be called ever, in any particular order.
637 * They are likely to be invoked when something WRITE_SYNC is used used.
638 * They should follow a caching pattern as shown below, so that any code
639 * using the word will get it's result no matter what happens.
642 * $workCallback = function () use ( &$result ) {
650 * @param callable $workCallback
653 public function addBusyCallback( callable
$workCallback ) {
654 $this->busyCallbacks
[] = $workCallback;
658 * Modify a cache update operation array for EventRelayer::notify()
660 * This is used for relayed writes, e.g. for broadcasting a change
661 * to multiple data-centers. If the array contains a 'val' field
662 * then the command involves setting a key to that value. Note that
663 * for simplicity, 'val' is always a simple scalar value. This method
664 * is used to possibly serialize the value and add any cache-specific
665 * key/values needed for the relayer daemon (e.g. memcached flags).
667 * @param array $event
671 public function modifySimpleRelayEvent( array $event ) {
676 * @param string $text
678 protected function debug( $text ) {
679 if ( $this->debugMode
) {
680 $this->logger
->debug( "{class} debug: $text", [
681 'class' => get_class( $this ),
687 * Convert an optionally relative time to an absolute time
688 * @param int $exptime
691 protected function convertExpiry( $exptime ) {
692 if ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) ) {
693 return time() +
$exptime;
700 * Convert an optionally absolute expiry time to a relative time. If an
701 * absolute time is specified which is in the past, use a short expiry time.
703 * @param int $exptime
706 protected function convertToRelative( $exptime ) {
707 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
709 if ( $exptime <= 0 ) {
719 * Check if a value is an integer
721 * @param mixed $value
724 protected function isInteger( $value ) {
725 return ( is_int( $value ) ||
ctype_digit( $value ) );
729 * Construct a cache key.
732 * @param string $keyspace
736 public function makeKeyInternal( $keyspace, $args ) {
738 foreach ( $args as $arg ) {
739 $arg = str_replace( ':', '%3A', $arg );
740 $key = $key . ':' . $arg;
742 return strtr( $key, ' ', '_' );
746 * Make a global cache key.
749 * @param string ... Key component (variadic)
752 public function makeGlobalKey() {
753 return $this->makeKeyInternal( 'global', func_get_args() );
757 * Make a cache key, scoped to this instance's keyspace.
760 * @param string ... Key component (variadic)
763 public function makeKey() {
764 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );
768 * @param integer $flag ATTR_* class constant
769 * @return integer QOS_* class constant
772 public function getQoS( $flag ) {
773 return isset( $this->attrMap
[$flag] ) ?
$this->attrMap
[$flag] : self
::QOS_UNKNOWN
;
777 * Merge the flag maps of one or more BagOStuff objects into a "lowest common denominator" map
779 * @param BagOStuff[] $bags
780 * @return integer[] Resulting flag map (class ATTR_* constant => class QOS_* constant)
782 protected function mergeFlagMaps( array $bags ) {
784 foreach ( $bags as $bag ) {
785 foreach ( $bag->attrMap
as $attr => $rank ) {
786 if ( isset( $map[$attr] ) ) {
787 $map[$attr] = min( $map[$attr], $rank );