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();
49 protected $lastError = self
::ERR_NONE
;
51 /** @var LoggerInterface */
55 private $debugMode = false;
57 /** Possible values for getLastError() */
58 const ERR_NONE
= 0; // no error
59 const ERR_NO_RESPONSE
= 1; // no response
60 const ERR_UNREACHABLE
= 2; // can't connect
61 const ERR_UNEXPECTED
= 3; // response gave some error
63 /** Bitfield constants for get()/getMulti() */
64 const READ_LATEST
= 1; // use latest data for replicated stores
65 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
67 public function __construct( array $params = array() ) {
68 if ( isset( $params['logger'] ) ) {
69 $this->setLogger( $params['logger'] );
71 $this->setLogger( new NullLogger() );
76 * @param LoggerInterface $logger
79 public function setLogger( LoggerInterface
$logger ) {
80 $this->logger
= $logger;
86 public function setDebug( $bool ) {
87 $this->debugMode
= $bool;
91 * Get an item with the given key, regenerating and setting it if not found
93 * If the callback returns false, then nothing is stored.
96 * @param int $ttl Time-to-live (seconds)
97 * @param callable $callback Callback that derives the new value
98 * @return mixed The cached value if found or the result of $callback otherwise
101 final public function getWithSetCallback( $key, $ttl, $callback ) {
102 $value = $this->get( $key );
104 if ( $value === false ) {
105 if ( !is_callable( $callback ) ) {
106 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
108 $value = call_user_func( $callback );
109 if ( $value !== false ) {
110 $this->set( $key, $value, $ttl );
118 * Get an item with the given key
120 * If the key includes a determistic input hash (e.g. the key can only have
121 * the correct value) or complete staleness checks are handled by the caller
122 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
123 * This lets tiered backends know they can safely upgrade a cached value to
124 * higher tiers using standard TTLs.
127 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
128 * @param integer $oldFlags [unused]
129 * @return mixed Returns false on failure and if the item does not exist
131 public function get( $key, $flags = 0, $oldFlags = null ) {
132 // B/C for ( $key, &$casToken = null, $flags = 0 )
133 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
135 return $this->doGet( $key, $flags );
140 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
141 * @return mixed Returns false on failure and if the item does not exist
143 abstract protected function doGet( $key, $flags = 0 );
146 * @note: This method is only needed if cas() is not is used for merge()
149 * @param mixed $casToken
150 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
151 * @return mixed Returns false on failure and if the item does not exist
153 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
154 throw new Exception( __METHOD__
. ' not implemented.' );
161 * @param mixed $value
162 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
163 * @return bool Success
165 abstract public function set( $key, $value, $exptime = 0 );
171 * @return bool True if the item was deleted or not found, false on failure
173 abstract public function delete( $key );
176 * Merge changes into the existing cache value (possibly creating a new one).
177 * The callback function returns the new value given the current value
178 * (which will be false if not present), and takes the arguments:
179 * (this BagOStuff, cache key, current value).
182 * @param callable $callback Callback method to be executed
183 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
184 * @param int $attempts The amount of times to attempt a merge in case of failure
185 * @return bool Success
186 * @throws InvalidArgumentException
188 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
189 if ( !is_callable( $callback ) ) {
190 throw new InvalidArgumentException( "Got invalid callback." );
193 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
197 * @see BagOStuff::merge()
200 * @param callable $callback Callback method to be executed
201 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
202 * @param int $attempts The amount of times to attempt a merge in case of failure
203 * @return bool Success
205 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
207 $this->clearLastError();
208 $casToken = null; // passed by reference
209 $currentValue = $this->getWithToken( $key, $casToken, BagOStuff
::READ_LATEST
);
210 if ( $this->getLastError() ) {
211 return false; // don't spam retries (retry only on races)
214 // Derive the new value from the old value
215 $value = call_user_func( $callback, $this, $key, $currentValue );
217 $this->clearLastError();
218 if ( $value === false ) {
219 $success = true; // do nothing
220 } elseif ( $currentValue === false ) {
221 // Try to create the key, failing if it gets created in the meantime
222 $success = $this->add( $key, $value, $exptime );
224 // Try to update the key, failing if it gets changed in the meantime
225 $success = $this->cas( $casToken, $key, $value, $exptime );
227 if ( $this->getLastError() ) {
228 return false; // IO error; don't spam retries
230 } while ( !$success && --$attempts );
236 * Check and set an item
238 * @param mixed $casToken
240 * @param mixed $value
241 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
242 * @return bool Success
245 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
246 throw new Exception( "CAS is not implemented in " . __CLASS__
);
250 * @see BagOStuff::merge()
253 * @param callable $callback Callback method to be executed
254 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
255 * @param int $attempts The amount of times to attempt a merge in case of failure
256 * @return bool Success
258 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
259 if ( !$this->lock( $key, 6 ) ) {
263 $this->clearLastError();
264 $currentValue = $this->get( $key, BagOStuff
::READ_LATEST
);
265 if ( $this->getLastError() ) {
268 // Derive the new value from the old value
269 $value = call_user_func( $callback, $this, $key, $currentValue );
270 if ( $value === false ) {
271 $success = true; // do nothing
273 $success = $this->set( $key, $value, $exptime ); // set the new value
277 if ( !$this->unlock( $key ) ) {
278 // this should never happen
279 trigger_error( "Could not release lock for key '$key'." );
286 * Acquire an advisory lock on a key string
288 * Note that if reentry is enabled, duplicate calls ignore $expiry
291 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
292 * @param int $expiry Lock expiry [optional]; 1 day maximum
293 * @param string $rclass Allow reentry if set and the current lock used this value
294 * @return bool Success
296 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
297 // Avoid deadlocks and allow lock reentry if specified
298 if ( isset( $this->locks
[$key] ) ) {
299 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
300 ++
$this->locks
[$key]['depth'];
307 $expiry = min( $expiry ?
: INF
, 86400 );
309 $this->clearLastError();
310 $timestamp = microtime( true ); // starting UNIX timestamp
311 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
313 } elseif ( $this->getLastError() ||
$timeout <= 0 ) {
314 $locked = false; // network partition or non-blocking
316 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
317 $sleep = 2 * $uRTT; // rough time to do get()+set()
319 $attempts = 0; // failed attempts
321 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
322 // Exponentially back off after failed attempts to avoid network spam.
323 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
326 usleep( $sleep ); // back off
327 $this->clearLastError();
328 $locked = $this->add( "{$key}:lock", 1, $expiry );
329 if ( $this->getLastError() ) {
330 $locked = false; // network partition
333 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
337 $this->locks
[$key] = array( 'class' => $rclass, 'depth' => 1 );
344 * Release an advisory lock on a key string
347 * @return bool Success
349 public function unlock( $key ) {
350 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
351 unset( $this->locks
[$key] );
353 return $this->delete( "{$key}:lock" );
360 * Get a lightweight exclusive self-unlocking lock
362 * Note that the same lock cannot be acquired twice.
364 * This is useful for task de-duplication or to avoid obtrusive
365 * (though non-corrupting) DB errors like INSERT key conflicts
366 * or deadlocks when using LOCK IN SHARE MODE.
369 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
370 * @param int $expiry Lock expiry [optional]; 1 day maximum
371 * @param string $rclass Allow reentry if set and the current lock used this value
372 * @return ScopedCallback|null Returns null on failure
375 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
376 $expiry = min( $expiry ?
: INF
, 86400 );
378 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
382 $lSince = microtime( true ); // lock timestamp
383 // PHP 5.3: Can't use $this in a closure
385 $logger = $this->logger
;
387 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
388 $latency = .050; // latency skew (err towards keeping lock present)
389 $age = ( microtime( true ) - $lSince +
$latency );
390 if ( ( $age +
$latency ) >= $expiry ) {
391 $logger->warning( "Lock for $key held too long ($age sec)." );
392 return; // expired; it's not "safe" to delete the key
394 $that->unlock( $key );
399 * Delete all objects expiring before a certain date.
400 * @param string $date The reference date in MW format
401 * @param callable|bool $progressCallback Optional, a function which will be called
402 * regularly during long-running operations with the percentage progress
403 * as the first parameter.
405 * @return bool Success, false if unimplemented
407 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
413 * Get an associative array containing the item for each of the keys that have items.
414 * @param array $keys List of strings
415 * @param integer $flags Bitfield; supports READ_LATEST [optional]
418 public function getMulti( array $keys, $flags = 0 ) {
420 foreach ( $keys as $key ) {
421 $val = $this->get( $key );
422 if ( $val !== false ) {
431 * @param array $data $key => $value assoc array
432 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
433 * @return bool Success
436 public function setMulti( array $data, $exptime = 0 ) {
438 foreach ( $data as $key => $value ) {
439 if ( !$this->set( $key, $value, $exptime ) ) {
448 * @param mixed $value
449 * @param int $exptime
450 * @return bool Success
452 public function add( $key, $value, $exptime = 0 ) {
453 if ( $this->get( $key ) === false ) {
454 return $this->set( $key, $value, $exptime );
456 return false; // key already set
460 * Increase stored value of $key by $value while preserving its TTL
461 * @param string $key Key to increase
462 * @param int $value Value to add to $key (Default 1)
463 * @return int|bool New value or false on failure
465 public function incr( $key, $value = 1 ) {
466 if ( !$this->lock( $key ) ) {
469 $n = $this->get( $key );
470 if ( $this->isInteger( $n ) ) { // key exists?
471 $n +
= intval( $value );
472 $this->set( $key, max( 0, $n ) ); // exptime?
476 $this->unlock( $key );
482 * Decrease stored value of $key by $value while preserving its TTL
485 * @return int|bool New value or false on failure
487 public function decr( $key, $value = 1 ) {
488 return $this->incr( $key, - $value );
492 * Increase stored value of $key by $value while preserving its TTL
494 * This will create the key with value $init and TTL $ttl if not present
503 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
504 return $this->incr( $key, $value ) ||
505 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
509 * Get the "last error" registered; clearLastError() should be called manually
510 * @return int ERR_* constant for the "last error" registry
513 public function getLastError() {
514 return $this->lastError
;
518 * Clear the "last error" registry
521 public function clearLastError() {
522 $this->lastError
= self
::ERR_NONE
;
526 * Set the "last error" registry
527 * @param int $err ERR_* constant
530 protected function setLastError( $err ) {
531 $this->lastError
= $err;
535 * Modify a cache update operation array for EventRelayer::notify()
537 * This is used for relayed writes, e.g. for broadcasting a change
538 * to multiple data-centers. If the array contains a 'val' field
539 * then the command involves setting a key to that value. Note that
540 * for simplicity, 'val' is always a simple scalar value. This method
541 * is used to possibly serialize the value and add any cache-specific
542 * key/values needed for the relayer daemon (e.g. memcached flags).
544 * @param array $event
548 public function modifySimpleRelayEvent( array $event ) {
553 * @param string $text
555 protected function debug( $text ) {
556 if ( $this->debugMode
) {
557 $this->logger
->debug( "{class} debug: $text", array(
558 'class' => get_class( $this ),
564 * Convert an optionally relative time to an absolute time
565 * @param int $exptime
568 protected function convertExpiry( $exptime ) {
569 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
570 return time() +
$exptime;
577 * Convert an optionally absolute expiry time to a relative time. If an
578 * absolute time is specified which is in the past, use a short expiry time.
580 * @param int $exptime
583 protected function convertToRelative( $exptime ) {
584 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
586 if ( $exptime <= 0 ) {
596 * Check if a value is an integer
598 * @param mixed $value
601 protected function isInteger( $value ) {
602 return ( is_int( $value ) ||
ctype_digit( $value ) );