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 = array();
50 protected $lastError = self
::ERR_NONE
;
53 protected $keyspace = 'local';
55 /** @var LoggerInterface */
59 private $debugMode = false;
61 /** Possible values for getLastError() */
62 const ERR_NONE
= 0; // no error
63 const ERR_NO_RESPONSE
= 1; // no response
64 const ERR_UNREACHABLE
= 2; // can't connect
65 const ERR_UNEXPECTED
= 3; // response gave some error
67 /** Bitfield constants for get()/getMulti() */
68 const READ_LATEST
= 1; // use latest data for replicated stores
69 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
70 /** Bitfield constants for set()/merge() */
71 const WRITE_SYNC
= 1; // synchronously write to all locations for replicated stores
72 const WRITE_CACHE_ONLY
= 2; // Only change state of the in-memory cache
74 public function __construct( array $params = array() ) {
75 if ( isset( $params['logger'] ) ) {
76 $this->setLogger( $params['logger'] );
78 $this->setLogger( new NullLogger() );
81 if ( isset( $params['keyspace'] ) ) {
82 $this->keyspace
= $params['keyspace'];
87 * @param LoggerInterface $logger
90 public function setLogger( LoggerInterface
$logger ) {
91 $this->logger
= $logger;
97 public function setDebug( $bool ) {
98 $this->debugMode
= $bool;
102 * Get an item with the given key, regenerating and setting it if not found
104 * If the callback returns false, then nothing is stored.
107 * @param int $ttl Time-to-live (seconds)
108 * @param callable $callback Callback that derives the new value
109 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
110 * @return mixed The cached value if found or the result of $callback otherwise
113 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
114 $value = $this->get( $key, $flags );
116 if ( $value === false ) {
117 if ( !is_callable( $callback ) ) {
118 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
120 $value = call_user_func( $callback );
121 if ( $value !== false ) {
122 $this->set( $key, $value, $ttl );
130 * Get an item with the given key
132 * If the key includes a determistic input hash (e.g. the key can only have
133 * the correct value) or complete staleness checks are handled by the caller
134 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
135 * This lets tiered backends know they can safely upgrade a cached value to
136 * higher tiers using standard TTLs.
139 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
140 * @param integer $oldFlags [unused]
141 * @return mixed Returns false on failure and if the item does not exist
143 public function get( $key, $flags = 0, $oldFlags = null ) {
144 // B/C for ( $key, &$casToken = null, $flags = 0 )
145 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
147 return $this->doGet( $key, $flags );
152 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
153 * @return mixed Returns false on failure and if the item does not exist
155 abstract protected function doGet( $key, $flags = 0 );
158 * @note: This method is only needed if merge() uses mergeViaCas()
161 * @param mixed $casToken
162 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
163 * @return mixed Returns false on failure and if the item does not exist
166 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
167 throw new Exception( __METHOD__
. ' not implemented.' );
174 * @param mixed $value
175 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
176 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
177 * @return bool Success
179 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
185 * @return bool True if the item was deleted or not found, false on failure
187 abstract public function delete( $key );
190 * Merge changes into the existing cache value (possibly creating a new one).
191 * The callback function returns the new value given the current value
192 * (which will be false if not present), and takes the arguments:
193 * (this BagOStuff, cache key, current value).
196 * @param callable $callback Callback method to be executed
197 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
198 * @param int $attempts The amount of times to attempt a merge in case of failure
199 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
200 * @return bool Success
201 * @throws InvalidArgumentException
203 public function merge( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
204 if ( !is_callable( $callback ) ) {
205 throw new InvalidArgumentException( "Got invalid callback." );
208 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
212 * @see BagOStuff::merge()
215 * @param callable $callback Callback method to be executed
216 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
217 * @param int $attempts The amount of times to attempt a merge in case of failure
218 * @return bool Success
220 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
222 $this->clearLastError();
223 $casToken = null; // passed by reference
224 $currentValue = $this->getWithToken( $key, $casToken, self
::READ_LATEST
);
225 if ( $this->getLastError() ) {
226 return false; // don't spam retries (retry only on races)
229 // Derive the new value from the old value
230 $value = call_user_func( $callback, $this, $key, $currentValue );
232 $this->clearLastError();
233 if ( $value === false ) {
234 $success = true; // do nothing
235 } elseif ( $currentValue === false ) {
236 // Try to create the key, failing if it gets created in the meantime
237 $success = $this->add( $key, $value, $exptime );
239 // Try to update the key, failing if it gets changed in the meantime
240 $success = $this->cas( $casToken, $key, $value, $exptime );
242 if ( $this->getLastError() ) {
243 return false; // IO error; don't spam retries
245 } while ( !$success && --$attempts );
251 * Check and set an item
253 * @param mixed $casToken
255 * @param mixed $value
256 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
257 * @return bool Success
260 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
261 throw new Exception( "CAS is not implemented in " . __CLASS__
);
265 * @see BagOStuff::merge()
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
274 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
275 if ( !$this->lock( $key, 6 ) ) {
279 $this->clearLastError();
280 $currentValue = $this->get( $key, self
::READ_LATEST
);
281 if ( $this->getLastError() ) {
284 // Derive the new value from the old value
285 $value = call_user_func( $callback, $this, $key, $currentValue );
286 if ( $value === false ) {
287 $success = true; // do nothing
289 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
293 if ( !$this->unlock( $key ) ) {
294 // this should never happen
295 trigger_error( "Could not release lock for key '$key'." );
302 * Acquire an advisory lock on a key string
304 * Note that if reentry is enabled, duplicate calls ignore $expiry
307 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
308 * @param int $expiry Lock expiry [optional]; 1 day maximum
309 * @param string $rclass Allow reentry if set and the current lock used this value
310 * @return bool Success
312 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
313 // Avoid deadlocks and allow lock reentry if specified
314 if ( isset( $this->locks
[$key] ) ) {
315 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
316 ++
$this->locks
[$key]['depth'];
323 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
325 $this->clearLastError();
326 $timestamp = microtime( true ); // starting UNIX timestamp
327 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
329 } elseif ( $this->getLastError() ||
$timeout <= 0 ) {
330 $locked = false; // network partition or non-blocking
332 // Estimate the RTT (us); use 1ms minimum for sanity
333 $uRTT = max( 1e3
, ceil( 1e6
* ( microtime( true ) - $timestamp ) ) );
334 $sleep = 2 * $uRTT; // rough time to do get()+set()
336 $attempts = 0; // failed attempts
338 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
339 // Exponentially back off after failed attempts to avoid network spam.
340 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
343 usleep( $sleep ); // back off
344 $this->clearLastError();
345 $locked = $this->add( "{$key}:lock", 1, $expiry );
346 if ( $this->getLastError() ) {
347 $locked = false; // network partition
350 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
354 $this->locks
[$key] = array( 'class' => $rclass, 'depth' => 1 );
361 * Release an advisory lock on a key string
364 * @return bool Success
366 public function unlock( $key ) {
367 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
368 unset( $this->locks
[$key] );
370 return $this->delete( "{$key}:lock" );
377 * Get a lightweight exclusive self-unlocking lock
379 * Note that the same lock cannot be acquired twice.
381 * This is useful for task de-duplication or to avoid obtrusive
382 * (though non-corrupting) DB errors like INSERT key conflicts
383 * or deadlocks when using LOCK IN SHARE MODE.
386 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
387 * @param int $expiry Lock expiry [optional]; 1 day maximum
388 * @param string $rclass Allow reentry if set and the current lock used this value
389 * @return ScopedCallback|null Returns null on failure
392 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
393 $expiry = min( $expiry ?
: INF
, self
::TTL_DAY
);
395 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
399 $lSince = microtime( true ); // lock timestamp
400 // PHP 5.3: Can't use $this in a closure
402 $logger = $this->logger
;
404 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
405 $latency = .050; // latency skew (err towards keeping lock present)
406 $age = ( microtime( true ) - $lSince +
$latency );
407 if ( ( $age +
$latency ) >= $expiry ) {
408 $logger->warning( "Lock for $key held too long ($age sec)." );
409 return; // expired; it's not "safe" to delete the key
411 $that->unlock( $key );
416 * Delete all objects expiring before a certain date.
417 * @param string $date The reference date in MW format
418 * @param callable|bool $progressCallback Optional, a function which will be called
419 * regularly during long-running operations with the percentage progress
420 * as the first parameter.
422 * @return bool Success, false if unimplemented
424 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
430 * Get an associative array containing the item for each of the keys that have items.
431 * @param array $keys List of strings
432 * @param integer $flags Bitfield; supports READ_LATEST [optional]
435 public function getMulti( array $keys, $flags = 0 ) {
437 foreach ( $keys as $key ) {
438 $val = $this->get( $key );
439 if ( $val !== false ) {
448 * @param array $data $key => $value assoc array
449 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
450 * @return bool Success
453 public function setMulti( array $data, $exptime = 0 ) {
455 foreach ( $data as $key => $value ) {
456 if ( !$this->set( $key, $value, $exptime ) ) {
465 * @param mixed $value
466 * @param int $exptime
467 * @return bool Success
469 public function add( $key, $value, $exptime = 0 ) {
470 if ( $this->get( $key ) === false ) {
471 return $this->set( $key, $value, $exptime );
473 return false; // key already set
477 * Increase stored value of $key by $value while preserving its TTL
478 * @param string $key Key to increase
479 * @param int $value Value to add to $key (Default 1)
480 * @return int|bool New value or false on failure
482 public function incr( $key, $value = 1 ) {
483 if ( !$this->lock( $key ) ) {
486 $n = $this->get( $key );
487 if ( $this->isInteger( $n ) ) { // key exists?
488 $n +
= intval( $value );
489 $this->set( $key, max( 0, $n ) ); // exptime?
493 $this->unlock( $key );
499 * Decrease stored value of $key by $value while preserving its TTL
502 * @return int|bool New value or false on failure
504 public function decr( $key, $value = 1 ) {
505 return $this->incr( $key, - $value );
509 * Increase stored value of $key by $value while preserving its TTL
511 * This will create the key with value $init and TTL $ttl instead if not present
517 * @return int|bool New value or false on failure
520 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
521 $newValue = $this->incr( $key, $value );
522 if ( $newValue === false ) {
523 // No key set; initialize
524 $newValue = $this->add( $key, (int)$init, $ttl ) ?
$init : false;
526 if ( $newValue === false ) {
527 // Raced out initializing; increment
528 $newValue = $this->incr( $key, $value );
535 * Get the "last error" registered; clearLastError() should be called manually
536 * @return int ERR_* constant for the "last error" registry
539 public function getLastError() {
540 return $this->lastError
;
544 * Clear the "last error" registry
547 public function clearLastError() {
548 $this->lastError
= self
::ERR_NONE
;
552 * Set the "last error" registry
553 * @param int $err ERR_* constant
556 protected function setLastError( $err ) {
557 $this->lastError
= $err;
561 * Modify a cache update operation array for EventRelayer::notify()
563 * This is used for relayed writes, e.g. for broadcasting a change
564 * to multiple data-centers. If the array contains a 'val' field
565 * then the command involves setting a key to that value. Note that
566 * for simplicity, 'val' is always a simple scalar value. This method
567 * is used to possibly serialize the value and add any cache-specific
568 * key/values needed for the relayer daemon (e.g. memcached flags).
570 * @param array $event
574 public function modifySimpleRelayEvent( array $event ) {
579 * @param string $text
581 protected function debug( $text ) {
582 if ( $this->debugMode
) {
583 $this->logger
->debug( "{class} debug: $text", array(
584 'class' => get_class( $this ),
590 * Convert an optionally relative time to an absolute time
591 * @param int $exptime
594 protected function convertExpiry( $exptime ) {
595 if ( $exptime != 0 && $exptime < ( 10 * self
::TTL_YEAR
) ) {
596 return time() +
$exptime;
603 * Convert an optionally absolute expiry time to a relative time. If an
604 * absolute time is specified which is in the past, use a short expiry time.
606 * @param int $exptime
609 protected function convertToRelative( $exptime ) {
610 if ( $exptime >= ( 10 * self
::TTL_YEAR
) ) {
612 if ( $exptime <= 0 ) {
622 * Check if a value is an integer
624 * @param mixed $value
627 protected function isInteger( $value ) {
628 return ( is_int( $value ) ||
ctype_digit( $value ) );
632 * Construct a cache key.
635 * @param string $keyspace
639 public function makeKeyInternal( $keyspace, $args ) {
641 foreach ( $args as $arg ) {
642 $arg = str_replace( ':', '%3A', $arg );
643 $key = $key . ':' . $arg;
645 return strtr( $key, ' ', '_' );
649 * Make a global cache key.
652 * @param string ... Key component (variadic)
655 public function makeGlobalKey() {
656 return $this->makeKeyInternal( 'global', func_get_args() );
660 * Make a cache key, scoped to this instance's keyspace.
663 * @param string ... Key component (variadic)
666 public function makeKey() {
667 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );