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
;
34 * interface is intended to be more or less compatible with
35 * the PHP memcached client.
37 * backends for local hash array and SQL table included:
39 * $bag = new HashBagOStuff();
40 * $bag = new SqlBagOStuff(); # connect to db first
45 abstract class BagOStuff
implements IExpiringStore
, LoggerAwareInterface
{
46 /** @var array[] Lock tracking */
47 protected $locks = [];
50 protected $lastError = self
::ERR_NONE
;
53 protected $keyspace = 'local';
55 /** @var LoggerInterface */
58 /** @var callback|null */
59 protected $asyncHandler;
62 private $debugMode = false;
65 private $duplicateKeyLookups = [];
68 private $reportDupes = false;
71 private $dupeTrackScheduled = false;
73 /** Possible values for getLastError() */
74 const ERR_NONE
= 0; // no error
75 const ERR_NO_RESPONSE
= 1; // no response
76 const ERR_UNREACHABLE
= 2; // can't connect
77 const ERR_UNEXPECTED
= 3; // response gave some error
79 /** Bitfield constants for get()/getMulti() */
80 const READ_LATEST
= 1; // use latest data for replicated stores
81 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
82 /** Bitfield constants for set()/merge() */
83 const WRITE_SYNC
= 1; // synchronously write to all locations for replicated stores
84 const WRITE_CACHE_ONLY
= 2; // Only change state of the in-memory cache
88 * - logger: Psr\Log\LoggerInterface instance
89 * - keyspace: Default keyspace for $this->makeKey()
90 * - asyncHandler: Callable to use for scheduling tasks after the web request ends.
91 * In CLI mode, it should run the task immediately.
92 * - reportDupes: Whether to emit warning log messages for all keys that were
93 * requested more than once (requires an asyncHandler).
94 * @param array $params
96 public function __construct( array $params = [] ) {
97 if ( isset( $params['logger'] ) ) {
98 $this->setLogger( $params['logger'] );
100 $this->setLogger( new NullLogger() );
103 if ( isset( $params['keyspace'] ) ) {
104 $this->keyspace
= $params['keyspace'];
107 $this->asyncHandler
= isset( $params['asyncHandler'] )
108 ?
$params['asyncHandler']
111 if ( !empty( $params['reportDupes'] ) && is_callable( $this->asyncHandler
) ) {
112 $this->reportDupes
= true;
117 * @param LoggerInterface $logger
120 public function setLogger( LoggerInterface
$logger ) {
121 $this->logger
= $logger;
127 public function setDebug( $bool ) {
128 $this->debugMode
= $bool;
132 * Get an item with the given key, regenerating and setting it if not found
134 * If the callback returns false, then nothing is stored.
137 * @param int $ttl Time-to-live (seconds)
138 * @param callable $callback Callback that derives the new value
139 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
140 * @return mixed The cached value if found or the result of $callback otherwise
143 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
144 $value = $this->get( $key, $flags );
146 if ( $value === false ) {
147 if ( !is_callable( $callback ) ) {
148 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
150 $value = call_user_func( $callback );
151 if ( $value !== false ) {
152 $this->set( $key, $value, $ttl );
160 * Get an item with the given key
162 * If the key includes a determistic input hash (e.g. the key can only have
163 * the correct value) or complete staleness checks are handled by the caller
164 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
165 * This lets tiered backends know they can safely upgrade a cached value to
166 * higher tiers using standard TTLs.
169 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
170 * @param integer $oldFlags [unused]
171 * @return mixed Returns false on failure and if the item does not exist
173 public function get( $key, $flags = 0, $oldFlags = null ) {
174 // B/C for ( $key, &$casToken = null, $flags = 0 )
175 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
177 $this->trackDuplicateKeys( $key );
179 return $this->doGet( $key, $flags );
183 * Track the number of times that a given key has been used.
186 private function trackDuplicateKeys( $key ) {
187 if ( !$this->reportDupes
) {
191 if ( !isset( $this->duplicateKeyLookups
[$key] ) ) {
192 // Track that we have seen this key. This N-1 counting style allows
193 // easy filtering with array_filter() later.
194 $this->duplicateKeyLookups
[$key] = 0;
196 $this->duplicateKeyLookups
[$key] +
= 1;
198 if ( $this->dupeTrackScheduled
=== false ) {
199 $this->dupeTrackScheduled
= true;
200 // Schedule a callback that logs keys processed more than once by get().
201 call_user_func( $this->asyncHandler
, function () {
202 $dups = array_filter( $this->duplicateKeyLookups
);
203 foreach ( $dups as $key => $count ) {
204 $this->logger
->warning(
205 'Duplicate get(): "{key}" fetched {count} times',
206 // Count is N-1 of the actual lookup count
207 [ 'key' => $key, 'count' => $count +
1, ]
217 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
218 * @return mixed Returns false on failure and if the item does not exist
220 abstract protected function doGet( $key, $flags = 0 );
223 * @note: This method is only needed if merge() uses mergeViaCas()
226 * @param mixed $casToken
227 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
228 * @return mixed Returns false on failure and if the item does not exist
231 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
232 throw new Exception( __METHOD__
. ' not implemented.' );
239 * @param mixed $value
240 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
241 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
242 * @return bool Success
244 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
250 * @return bool True if the item was deleted or not found, false on failure
252 abstract public function delete( $key );
255 * Merge changes into the existing cache value (possibly creating a new one).
256 * The callback function returns the new value given the current value
257 * (which will be false if not present), and takes the arguments:
258 * (this BagOStuff, cache key, current value).
261 * @param callable $callback Callback method to be executed
262 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
263 * @param int $attempts The amount of times to attempt a merge in case of failure
264 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
265 * @return bool Success
266 * @throws InvalidArgumentException
268 public function merge( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
269 if ( !is_callable( $callback ) ) {
270 throw new InvalidArgumentException( "Got invalid callback." );
273 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
277 * @see BagOStuff::merge()
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 * @return bool Success
285 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
287 $this->clearLastError();
288 $casToken = null; // passed by reference
289 $currentValue = $this->getWithToken( $key, $casToken, self
::READ_LATEST
);
290 if ( $this->getLastError() ) {
291 return false; // don't spam retries (retry only on races)
294 // Derive the new value from the old value
295 $value = call_user_func( $callback, $this, $key, $currentValue );
297 $this->clearLastError();
298 if ( $value === false ) {
299 $success = true; // do nothing
300 } elseif ( $currentValue === false ) {
301 // Try to create the key, failing if it gets created in the meantime
302 $success = $this->add( $key, $value, $exptime );
304 // Try to update the key, failing if it gets changed in the meantime
305 $success = $this->cas( $casToken, $key, $value, $exptime );
307 if ( $this->getLastError() ) {
308 return false; // IO error; don't spam retries
310 } while ( !$success && --$attempts );
316 * Check and set an item
318 * @param mixed $casToken
320 * @param mixed $value
321 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
322 * @return bool Success
325 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
326 throw new Exception( "CAS is not implemented in " . __CLASS__
);
330 * @see BagOStuff::merge()
333 * @param callable $callback Callback method to be executed
334 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
335 * @param int $attempts The amount of times to attempt a merge in case of failure
336 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
337 * @return bool Success
339 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
340 if ( !$this->lock( $key, 6 ) ) {
344 $this->clearLastError();
345 $currentValue = $this->get( $key, self
::READ_LATEST
);
346 if ( $this->getLastError() ) {
349 // Derive the new value from the old value
350 $value = call_user_func( $callback, $this, $key, $currentValue );
351 if ( $value === false ) {
352 $success = true; // do nothing
354 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
358 if ( !$this->unlock( $key ) ) {
359 // this should never happen
360 trigger_error( "Could not release lock for key '$key'." );
367 * Acquire an advisory lock on a key string
369 * Note that if reentry is enabled, duplicate calls ignore $expiry
372 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
373 * @param int $expiry Lock expiry [optional]; 1 day maximum
374 * @param string $rclass Allow reentry if set and the current lock used this value
375 * @return bool Success
377 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
378 // Avoid deadlocks and allow lock reentry if specified
379 if ( isset( $this->locks
[$key] ) ) {
380 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
381 ++
$this->locks
[$key]['depth'];
388 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
390 $this->clearLastError();
391 $timestamp = microtime( true ); // starting UNIX timestamp
392 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
394 } elseif ( $this->getLastError() ||
$timeout <= 0 ) {
395 $locked = false; // network partition or non-blocking
397 // Estimate the RTT (us); use 1ms minimum for sanity
398 $uRTT = max( 1e3
, ceil( 1e6
* ( microtime( true ) - $timestamp ) ) );
399 $sleep = 2 * $uRTT; // rough time to do get()+set()
401 $attempts = 0; // failed attempts
403 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
404 // Exponentially back off after failed attempts to avoid network spam.
405 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
408 usleep( $sleep ); // back off
409 $this->clearLastError();
410 $locked = $this->add( "{$key}:lock", 1, $expiry );
411 if ( $this->getLastError() ) {
412 $locked = false; // network partition
415 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
419 $this->locks
[$key] = [ 'class' => $rclass, 'depth' => 1 ];
426 * Release an advisory lock on a key string
429 * @return bool Success
431 public function unlock( $key ) {
432 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
433 unset( $this->locks
[$key] );
435 return $this->delete( "{$key}:lock" );
442 * Get a lightweight exclusive self-unlocking lock
444 * Note that the same lock cannot be acquired twice.
446 * This is useful for task de-duplication or to avoid obtrusive
447 * (though non-corrupting) DB errors like INSERT key conflicts
448 * or deadlocks when using LOCK IN SHARE MODE.
451 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
452 * @param int $expiry Lock expiry [optional]; 1 day maximum
453 * @param string $rclass Allow reentry if set and the current lock used this value
454 * @return ScopedCallback|null Returns null on failure
457 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
458 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
460 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
464 $lSince = microtime( true ); // lock timestamp
466 return new ScopedCallback( function() use ( $key, $lSince, $expiry ) {
467 $latency = .050; // latency skew (err towards keeping lock present)
468 $age = ( microtime( true ) - $lSince +
$latency );
469 if ( ( $age +
$latency ) >= $expiry ) {
470 $this->logger
->warning( "Lock for $key held too long ($age sec)." );
471 return; // expired; it's not "safe" to delete the key
473 $this->unlock( $key );
478 * Delete all objects expiring before a certain date.
479 * @param string $date The reference date in MW format
480 * @param callable|bool $progressCallback Optional, a function which will be called
481 * regularly during long-running operations with the percentage progress
482 * as the first parameter.
484 * @return bool Success, false if unimplemented
486 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
492 * Get an associative array containing the item for each of the keys that have items.
493 * @param array $keys List of strings
494 * @param integer $flags Bitfield; supports READ_LATEST [optional]
497 public function getMulti( array $keys, $flags = 0 ) {
499 foreach ( $keys as $key ) {
500 $val = $this->get( $key );
501 if ( $val !== false ) {
510 * @param array $data $key => $value assoc array
511 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
512 * @return bool Success
515 public function setMulti( array $data, $exptime = 0 ) {
517 foreach ( $data as $key => $value ) {
518 if ( !$this->set( $key, $value, $exptime ) ) {
527 * @param mixed $value
528 * @param int $exptime
529 * @return bool Success
531 public function add( $key, $value, $exptime = 0 ) {
532 if ( $this->get( $key ) === false ) {
533 return $this->set( $key, $value, $exptime );
535 return false; // key already set
539 * Increase stored value of $key by $value while preserving its TTL
540 * @param string $key Key to increase
541 * @param int $value Value to add to $key (Default 1)
542 * @return int|bool New value or false on failure
544 public function incr( $key, $value = 1 ) {
545 if ( !$this->lock( $key ) ) {
548 $n = $this->get( $key );
549 if ( $this->isInteger( $n ) ) { // key exists?
550 $n +
= intval( $value );
551 $this->set( $key, max( 0, $n ) ); // exptime?
555 $this->unlock( $key );
561 * Decrease stored value of $key by $value while preserving its TTL
564 * @return int|bool New value or false on failure
566 public function decr( $key, $value = 1 ) {
567 return $this->incr( $key, - $value );
571 * Increase stored value of $key by $value while preserving its TTL
573 * This will create the key with value $init and TTL $ttl instead if not present
579 * @return int|bool New value or false on failure
582 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
583 $newValue = $this->incr( $key, $value );
584 if ( $newValue === false ) {
585 // No key set; initialize
586 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
588 if ( $newValue === false ) {
589 // Raced out initializing; increment
590 $newValue = $this->incr( $key, $value );
597 * Get the "last error" registered; clearLastError() should be called manually
598 * @return int ERR_* constant for the "last error" registry
601 public function getLastError() {
602 return $this->lastError
;
606 * Clear the "last error" registry
609 public function clearLastError() {
610 $this->lastError
= self
::ERR_NONE
;
614 * Set the "last error" registry
615 * @param int $err ERR_* constant
618 protected function setLastError( $err ) {
619 $this->lastError
= $err;
623 * Modify a cache update operation array for EventRelayer::notify()
625 * This is used for relayed writes, e.g. for broadcasting a change
626 * to multiple data-centers. If the array contains a 'val' field
627 * then the command involves setting a key to that value. Note that
628 * for simplicity, 'val' is always a simple scalar value. This method
629 * is used to possibly serialize the value and add any cache-specific
630 * key/values needed for the relayer daemon (e.g. memcached flags).
632 * @param array $event
636 public function modifySimpleRelayEvent( array $event ) {
641 * @param string $text
643 protected function debug( $text ) {
644 if ( $this->debugMode
) {
645 $this->logger
->debug( "{class} debug: $text", [
646 'class' => get_class( $this ),
652 * Convert an optionally relative time to an absolute time
653 * @param int $exptime
656 protected function convertExpiry( $exptime ) {
657 if ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) ) {
658 return time() +
$exptime;
665 * Convert an optionally absolute expiry time to a relative time. If an
666 * absolute time is specified which is in the past, use a short expiry time.
668 * @param int $exptime
671 protected function convertToRelative( $exptime ) {
672 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
674 if ( $exptime <= 0 ) {
684 * Check if a value is an integer
686 * @param mixed $value
689 protected function isInteger( $value ) {
690 return ( is_int( $value ) ||
ctype_digit( $value ) );
694 * Construct a cache key.
697 * @param string $keyspace
701 public function makeKeyInternal( $keyspace, $args ) {
703 foreach ( $args as $arg ) {
704 $arg = str_replace( ':', '%3A', $arg );
705 $key = $key . ':' . $arg;
707 return strtr( $key, ' ', '_' );
711 * Make a global cache key.
714 * @param string ... Key component (variadic)
717 public function makeGlobalKey() {
718 return $this->makeKeyInternal( 'global', func_get_args() );
722 * Make a cache key, scoped to this instance's keyspace.
725 * @param string ... Key component (variadic)
728 public function makeKey() {
729 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );