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 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
71 public function __construct( array $params = array() ) {
72 if ( isset( $params['logger'] ) ) {
73 $this->setLogger( $params['logger'] );
75 $this->setLogger( new NullLogger() );
78 if ( isset( $params['keyspace'] ) ) {
79 $this->keyspace
= $params['keyspace'];
84 * @param LoggerInterface $logger
87 public function setLogger( LoggerInterface
$logger ) {
88 $this->logger
= $logger;
94 public function setDebug( $bool ) {
95 $this->debugMode
= $bool;
99 * Get an item with the given key, regenerating and setting it if not found
101 * If the callback returns false, then nothing is stored.
104 * @param int $ttl Time-to-live (seconds)
105 * @param callable $callback Callback that derives the new value
106 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
107 * @return mixed The cached value if found or the result of $callback otherwise
110 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
111 $value = $this->get( $key, $flags );
113 if ( $value === false ) {
114 if ( !is_callable( $callback ) ) {
115 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
117 $value = call_user_func( $callback );
118 if ( $value !== false ) {
119 $this->set( $key, $value, $ttl );
127 * Get an item with the given key
129 * If the key includes a determistic input hash (e.g. the key can only have
130 * the correct value) or complete staleness checks are handled by the caller
131 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
132 * This lets tiered backends know they can safely upgrade a cached value to
133 * higher tiers using standard TTLs.
136 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
137 * @param integer $oldFlags [unused]
138 * @return mixed Returns false on failure and if the item does not exist
140 public function get( $key, $flags = 0, $oldFlags = null ) {
141 // B/C for ( $key, &$casToken = null, $flags = 0 )
142 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
144 return $this->doGet( $key, $flags );
149 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
150 * @return mixed Returns false on failure and if the item does not exist
152 abstract protected function doGet( $key, $flags = 0 );
155 * @note: This method is only needed if merge() uses mergeViaCas()
158 * @param mixed $casToken
159 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
160 * @return mixed Returns false on failure and if the item does not exist
162 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
163 throw new Exception( __METHOD__
. ' not implemented.' );
170 * @param mixed $value
171 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
172 * @return bool Success
174 abstract public function set( $key, $value, $exptime = 0 );
180 * @return bool True if the item was deleted or not found, false on failure
182 abstract public function delete( $key );
185 * Merge changes into the existing cache value (possibly creating a new one).
186 * The callback function returns the new value given the current value
187 * (which will be false if not present), and takes the arguments:
188 * (this BagOStuff, cache key, current value).
191 * @param callable $callback Callback method to be executed
192 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
193 * @param int $attempts The amount of times to attempt a merge in case of failure
194 * @return bool Success
195 * @throws InvalidArgumentException
197 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
198 if ( !is_callable( $callback ) ) {
199 throw new InvalidArgumentException( "Got invalid callback." );
202 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
206 * @see BagOStuff::merge()
209 * @param callable $callback Callback method to be executed
210 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
211 * @param int $attempts The amount of times to attempt a merge in case of failure
212 * @return bool Success
214 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
216 $this->clearLastError();
217 $casToken = null; // passed by reference
218 $currentValue = $this->getWithToken( $key, $casToken, BagOStuff
::READ_LATEST
);
219 if ( $this->getLastError() ) {
220 return false; // don't spam retries (retry only on races)
223 // Derive the new value from the old value
224 $value = call_user_func( $callback, $this, $key, $currentValue );
226 $this->clearLastError();
227 if ( $value === false ) {
228 $success = true; // do nothing
229 } elseif ( $currentValue === false ) {
230 // Try to create the key, failing if it gets created in the meantime
231 $success = $this->add( $key, $value, $exptime );
233 // Try to update the key, failing if it gets changed in the meantime
234 $success = $this->cas( $casToken, $key, $value, $exptime );
236 if ( $this->getLastError() ) {
237 return false; // IO error; don't spam retries
239 } while ( !$success && --$attempts );
245 * Check and set an item
247 * @param mixed $casToken
249 * @param mixed $value
250 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
251 * @return bool Success
254 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
255 throw new Exception( "CAS is not implemented in " . __CLASS__
);
259 * @see BagOStuff::merge()
262 * @param callable $callback Callback method to be executed
263 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
264 * @param int $attempts The amount of times to attempt a merge in case of failure
265 * @return bool Success
267 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
268 if ( !$this->lock( $key, 6 ) ) {
272 $this->clearLastError();
273 $currentValue = $this->get( $key, BagOStuff
::READ_LATEST
);
274 if ( $this->getLastError() ) {
277 // Derive the new value from the old value
278 $value = call_user_func( $callback, $this, $key, $currentValue );
279 if ( $value === false ) {
280 $success = true; // do nothing
282 $success = $this->set( $key, $value, $exptime ); // set the new value
286 if ( !$this->unlock( $key ) ) {
287 // this should never happen
288 trigger_error( "Could not release lock for key '$key'." );
295 * Acquire an advisory lock on a key string
297 * Note that if reentry is enabled, duplicate calls ignore $expiry
300 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
301 * @param int $expiry Lock expiry [optional]; 1 day maximum
302 * @param string $rclass Allow reentry if set and the current lock used this value
303 * @return bool Success
305 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
306 // Avoid deadlocks and allow lock reentry if specified
307 if ( isset( $this->locks
[$key] ) ) {
308 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
309 ++
$this->locks
[$key]['depth'];
316 $expiry = min( $expiry ?
: INF
, 86400 );
318 $this->clearLastError();
319 $timestamp = microtime( true ); // starting UNIX timestamp
320 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
322 } elseif ( $this->getLastError() ||
$timeout <= 0 ) {
323 $locked = false; // network partition or non-blocking
325 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
326 $sleep = 2 * $uRTT; // rough time to do get()+set()
328 $attempts = 0; // failed attempts
330 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
331 // Exponentially back off after failed attempts to avoid network spam.
332 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
335 usleep( $sleep ); // back off
336 $this->clearLastError();
337 $locked = $this->add( "{$key}:lock", 1, $expiry );
338 if ( $this->getLastError() ) {
339 $locked = false; // network partition
342 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
346 $this->locks
[$key] = array( 'class' => $rclass, 'depth' => 1 );
353 * Release an advisory lock on a key string
356 * @return bool Success
358 public function unlock( $key ) {
359 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
360 unset( $this->locks
[$key] );
362 return $this->delete( "{$key}:lock" );
369 * Get a lightweight exclusive self-unlocking lock
371 * Note that the same lock cannot be acquired twice.
373 * This is useful for task de-duplication or to avoid obtrusive
374 * (though non-corrupting) DB errors like INSERT key conflicts
375 * or deadlocks when using LOCK IN SHARE MODE.
378 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
379 * @param int $expiry Lock expiry [optional]; 1 day maximum
380 * @param string $rclass Allow reentry if set and the current lock used this value
381 * @return ScopedCallback|null Returns null on failure
384 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
385 $expiry = min( $expiry ?
: INF
, 86400 );
387 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
391 $lSince = microtime( true ); // lock timestamp
392 // PHP 5.3: Can't use $this in a closure
394 $logger = $this->logger
;
396 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
397 $latency = .050; // latency skew (err towards keeping lock present)
398 $age = ( microtime( true ) - $lSince +
$latency );
399 if ( ( $age +
$latency ) >= $expiry ) {
400 $logger->warning( "Lock for $key held too long ($age sec)." );
401 return; // expired; it's not "safe" to delete the key
403 $that->unlock( $key );
408 * Delete all objects expiring before a certain date.
409 * @param string $date The reference date in MW format
410 * @param callable|bool $progressCallback Optional, a function which will be called
411 * regularly during long-running operations with the percentage progress
412 * as the first parameter.
414 * @return bool Success, false if unimplemented
416 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
422 * Get an associative array containing the item for each of the keys that have items.
423 * @param array $keys List of strings
424 * @param integer $flags Bitfield; supports READ_LATEST [optional]
427 public function getMulti( array $keys, $flags = 0 ) {
429 foreach ( $keys as $key ) {
430 $val = $this->get( $key );
431 if ( $val !== false ) {
440 * @param array $data $key => $value assoc array
441 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
442 * @return bool Success
445 public function setMulti( array $data, $exptime = 0 ) {
447 foreach ( $data as $key => $value ) {
448 if ( !$this->set( $key, $value, $exptime ) ) {
457 * @param mixed $value
458 * @param int $exptime
459 * @return bool Success
461 public function add( $key, $value, $exptime = 0 ) {
462 if ( $this->get( $key ) === false ) {
463 return $this->set( $key, $value, $exptime );
465 return false; // key already set
469 * Increase stored value of $key by $value while preserving its TTL
470 * @param string $key Key to increase
471 * @param int $value Value to add to $key (Default 1)
472 * @return int|bool New value or false on failure
474 public function incr( $key, $value = 1 ) {
475 if ( !$this->lock( $key ) ) {
478 $n = $this->get( $key );
479 if ( $this->isInteger( $n ) ) { // key exists?
480 $n +
= intval( $value );
481 $this->set( $key, max( 0, $n ) ); // exptime?
485 $this->unlock( $key );
491 * Decrease stored value of $key by $value while preserving its TTL
494 * @return int|bool New value or false on failure
496 public function decr( $key, $value = 1 ) {
497 return $this->incr( $key, - $value );
501 * Increase stored value of $key by $value while preserving its TTL
503 * This will create the key with value $init and TTL $ttl if not present
512 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
513 return $this->incr( $key, $value ) ||
514 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
518 * Get the "last error" registered; clearLastError() should be called manually
519 * @return int ERR_* constant for the "last error" registry
522 public function getLastError() {
523 return $this->lastError
;
527 * Clear the "last error" registry
530 public function clearLastError() {
531 $this->lastError
= self
::ERR_NONE
;
535 * Set the "last error" registry
536 * @param int $err ERR_* constant
539 protected function setLastError( $err ) {
540 $this->lastError
= $err;
544 * Modify a cache update operation array for EventRelayer::notify()
546 * This is used for relayed writes, e.g. for broadcasting a change
547 * to multiple data-centers. If the array contains a 'val' field
548 * then the command involves setting a key to that value. Note that
549 * for simplicity, 'val' is always a simple scalar value. This method
550 * is used to possibly serialize the value and add any cache-specific
551 * key/values needed for the relayer daemon (e.g. memcached flags).
553 * @param array $event
557 public function modifySimpleRelayEvent( array $event ) {
562 * @param string $text
564 protected function debug( $text ) {
565 if ( $this->debugMode
) {
566 $this->logger
->debug( "{class} debug: $text", array(
567 'class' => get_class( $this ),
573 * Convert an optionally relative time to an absolute time
574 * @param int $exptime
577 protected function convertExpiry( $exptime ) {
578 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
579 return time() +
$exptime;
586 * Convert an optionally absolute expiry time to a relative time. If an
587 * absolute time is specified which is in the past, use a short expiry time.
589 * @param int $exptime
592 protected function convertToRelative( $exptime ) {
593 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
595 if ( $exptime <= 0 ) {
605 * Check if a value is an integer
607 * @param mixed $value
610 protected function isInteger( $value ) {
611 return ( is_int( $value ) ||
ctype_digit( $value ) );
615 * Construct a cache key.
618 * @param string $keyspace
622 public function makeKeyInternal( $keyspace, $args ) {
623 $key = $keyspace . ':' . implode( ':', $args );
624 return strtr( $key, ' ', '_' );
628 * Make a global cache key.
631 * @param string ... Key component (variadic)
634 public function makeGlobalKey() {
635 return $this->makeKeyInternal( 'global', func_get_args() );
639 * Make a cache key, scoped to this instance's keyspace.
642 * @param string ... Key component (variadic)
645 public function makeKey() {
646 return $this->makeKeyInternal( $this->keyspace
, func_get_args() );