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
66 public function __construct( array $params = array() ) {
67 if ( isset( $params['logger'] ) ) {
68 $this->setLogger( $params['logger'] );
70 $this->setLogger( new NullLogger() );
75 * @param LoggerInterface $logger
78 public function setLogger( LoggerInterface
$logger ) {
79 $this->logger
= $logger;
85 public function setDebug( $bool ) {
86 $this->debugMode
= $bool;
90 * Get an item with the given key. Returns false if it does not exist.
92 * @param mixed $casToken [optional]
93 * @param integer $flags Bitfield; supports READ_LATEST [optional]
94 * @return mixed Returns false on failure
96 abstract public function get( $key, &$casToken = null, $flags = 0 );
101 * @param mixed $value
102 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
103 * @return bool Success
105 abstract public function set( $key, $value, $exptime = 0 );
110 * @return bool True if the item was deleted or not found, false on failure
112 abstract public function delete( $key );
115 * Merge changes into the existing cache value (possibly creating a new one).
116 * The callback function returns the new value given the current value
117 * (which will be false if not present), and takes the arguments:
118 * (this BagOStuff, cache key, current value).
121 * @param callable $callback Callback method to be executed
122 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
123 * @param int $attempts The amount of times to attempt a merge in case of failure
124 * @return bool Success
125 * @throws InvalidArgumentException
127 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
128 if ( !is_callable( $callback ) ) {
129 throw new InvalidArgumentException( "Got invalid callback." );
132 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
136 * @see BagOStuff::merge()
139 * @param callable $callback Callback method to be executed
140 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
141 * @param int $attempts The amount of times to attempt a merge in case of failure
142 * @return bool Success
144 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
146 $this->clearLastError();
147 $casToken = null; // passed by reference
148 $currentValue = $this->get( $key, $casToken );
149 if ( $this->getLastError() ) {
150 return false; // don't spam retries (retry only on races)
153 // Derive the new value from the old value
154 $value = call_user_func( $callback, $this, $key, $currentValue );
156 $this->clearLastError();
157 if ( $value === false ) {
158 $success = true; // do nothing
159 } elseif ( $currentValue === false ) {
160 // Try to create the key, failing if it gets created in the meantime
161 $success = $this->add( $key, $value, $exptime );
163 // Try to update the key, failing if it gets changed in the meantime
164 $success = $this->cas( $casToken, $key, $value, $exptime );
166 if ( $this->getLastError() ) {
167 return false; // IO error; don't spam retries
169 } while ( !$success && --$attempts );
175 * Check and set an item
177 * @param mixed $casToken
179 * @param mixed $value
180 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
181 * @return bool Success
184 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
185 throw new Exception( "CAS is not implemented in " . __CLASS__
);
189 * @see BagOStuff::merge()
192 * @param callable $callback Callback method to be executed
193 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
194 * @param int $attempts The amount of times to attempt a merge in case of failure
195 * @return bool Success
197 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
198 if ( !$this->lock( $key, 6 ) ) {
202 $this->clearLastError();
203 $currentValue = $this->get( $key );
204 if ( $this->getLastError() ) {
207 // Derive the new value from the old value
208 $value = call_user_func( $callback, $this, $key, $currentValue );
209 if ( $value === false ) {
210 $success = true; // do nothing
212 $success = $this->set( $key, $value, $exptime ); // set the new value
216 if ( !$this->unlock( $key ) ) {
217 // this should never happen
218 trigger_error( "Could not release lock for key '$key'." );
225 * Acquire an advisory lock on a key string
227 * Note that if reentry is enabled, duplicate calls ignore $expiry
230 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
231 * @param int $expiry Lock expiry [optional]; 1 day maximum
232 * @param string $rclass Allow reentry if set and the current lock used this value
233 * @return bool Success
235 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
236 // Avoid deadlocks and allow lock reentry if specified
237 if ( isset( $this->locks
[$key] ) ) {
238 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
239 ++
$this->locks
[$key]['depth'];
246 $expiry = min( $expiry ?
: INF
, 86400 );
248 $this->clearLastError();
249 $timestamp = microtime( true ); // starting UNIX timestamp
250 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
252 } elseif ( $this->getLastError() ||
$timeout <= 0 ) {
253 $locked = false; // network partition or non-blocking
255 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
256 $sleep = 2 * $uRTT; // rough time to do get()+set()
258 $attempts = 0; // failed attempts
260 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
261 // Exponentially back off after failed attempts to avoid network spam.
262 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
265 usleep( $sleep ); // back off
266 $this->clearLastError();
267 $locked = $this->add( "{$key}:lock", 1, $expiry );
268 if ( $this->getLastError() ) {
269 $locked = false; // network partition
272 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
276 $this->locks
[$key] = array( 'class' => $rclass, 'depth' => 1 );
283 * Release an advisory lock on a key string
286 * @return bool Success
288 public function unlock( $key ) {
289 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
290 unset( $this->locks
[$key] );
292 return $this->delete( "{$key}:lock" );
299 * Get a lightweight exclusive self-unlocking lock
301 * Note that the same lock cannot be acquired twice.
303 * This is useful for task de-duplication or to avoid obtrusive
304 * (though non-corrupting) DB errors like INSERT key conflicts
305 * or deadlocks when using LOCK IN SHARE MODE.
308 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
309 * @param int $expiry Lock expiry [optional]; 1 day maximum
310 * @param string $rclass Allow reentry if set and the current lock used this value
311 * @return ScopedCallback|null Returns null on failure
314 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
315 $expiry = min( $expiry ?
: INF
, 86400 );
317 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
321 $lSince = microtime( true ); // lock timestamp
322 // PHP 5.3: Can't use $this in a closure
324 $logger = $this->logger
;
326 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
327 $latency = .050; // latency skew (err towards keeping lock present)
328 $age = ( microtime( true ) - $lSince +
$latency );
329 if ( ( $age +
$latency ) >= $expiry ) {
330 $logger->warning( "Lock for $key held too long ($age sec)." );
331 return; // expired; it's not "safe" to delete the key
333 $that->unlock( $key );
338 * Delete all objects expiring before a certain date.
339 * @param string $date The reference date in MW format
340 * @param callable|bool $progressCallback Optional, a function which will be called
341 * regularly during long-running operations with the percentage progress
342 * as the first parameter.
344 * @return bool Success, false if unimplemented
346 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
352 * Get an associative array containing the item for each of the keys that have items.
353 * @param array $keys List of strings
354 * @param integer $flags Bitfield; supports READ_LATEST [optional]
357 public function getMulti( array $keys, $flags = 0 ) {
359 foreach ( $keys as $key ) {
360 $val = $this->get( $key );
361 if ( $val !== false ) {
370 * @param array $data $key => $value assoc array
371 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
372 * @return bool Success
375 public function setMulti( array $data, $exptime = 0 ) {
377 foreach ( $data as $key => $value ) {
378 if ( !$this->set( $key, $value, $exptime ) ) {
387 * @param mixed $value
388 * @param int $exptime
389 * @return bool Success
391 public function add( $key, $value, $exptime = 0 ) {
392 if ( $this->get( $key ) === false ) {
393 return $this->set( $key, $value, $exptime );
395 return false; // key already set
399 * Increase stored value of $key by $value while preserving its TTL
400 * @param string $key Key to increase
401 * @param int $value Value to add to $key (Default 1)
402 * @return int|bool New value or false on failure
404 public function incr( $key, $value = 1 ) {
405 if ( !$this->lock( $key ) ) {
408 $n = $this->get( $key );
409 if ( $this->isInteger( $n ) ) { // key exists?
410 $n +
= intval( $value );
411 $this->set( $key, max( 0, $n ) ); // exptime?
415 $this->unlock( $key );
421 * Decrease stored value of $key by $value while preserving its TTL
424 * @return int|bool New value or false on failure
426 public function decr( $key, $value = 1 ) {
427 return $this->incr( $key, - $value );
431 * Increase stored value of $key by $value while preserving its TTL
433 * This will create the key with value $init and TTL $ttl if not present
442 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
443 return $this->incr( $key, $value ) ||
444 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
448 * Get the "last error" registered; clearLastError() should be called manually
449 * @return int ERR_* constant for the "last error" registry
452 public function getLastError() {
453 return $this->lastError
;
457 * Clear the "last error" registry
460 public function clearLastError() {
461 $this->lastError
= self
::ERR_NONE
;
465 * Set the "last error" registry
466 * @param int $err ERR_* constant
469 protected function setLastError( $err ) {
470 $this->lastError
= $err;
474 * Modify a cache update operation array for EventRelayer::notify()
476 * This is used for relayed writes, e.g. for broadcasting a change
477 * to multiple data-centers. If the array contains a 'val' field
478 * then the command involves setting a key to that value. Note that
479 * for simplicity, 'val' is always a simple scalar value. This method
480 * is used to possibly serialize the value and add any cache-specific
481 * key/values needed for the relayer daemon (e.g. memcached flags).
483 * @param array $event
487 public function modifySimpleRelayEvent( array $event ) {
492 * @param string $text
494 protected function debug( $text ) {
495 if ( $this->debugMode
) {
496 $this->logger
->debug( "{class} debug: $text", array(
497 'class' => get_class( $this ),
503 * Convert an optionally relative time to an absolute time
504 * @param int $exptime
507 protected function convertExpiry( $exptime ) {
508 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
509 return time() +
$exptime;
516 * Convert an optionally absolute expiry time to a relative time. If an
517 * absolute time is specified which is in the past, use a short expiry time.
519 * @param int $exptime
522 protected function convertToRelative( $exptime ) {
523 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
525 if ( $exptime <= 0 ) {
535 * Check if a value is an integer
537 * @param mixed $value
540 protected function isInteger( $value ) {
541 return ( is_int( $value ) ||
ctype_digit( $value ) );