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 private $debugMode = false;
49 protected $lastError = self
::ERR_NONE
;
52 * @var LoggerInterface
56 /** Possible values for getLastError() */
57 const ERR_NONE
= 0; // no error
58 const ERR_NO_RESPONSE
= 1; // no response
59 const ERR_UNREACHABLE
= 2; // can't connect
60 const ERR_UNEXPECTED
= 3; // response gave some error
62 public function __construct( array $params = array() ) {
63 if ( isset( $params['logger'] ) ) {
64 $this->setLogger( $params['logger'] );
66 $this->setLogger( new NullLogger() );
71 * @param LoggerInterface $logger
74 public function setLogger( LoggerInterface
$logger ) {
75 $this->logger
= $logger;
81 public function setDebug( $bool ) {
82 $this->debugMode
= $bool;
86 * Get an item with the given key. Returns false if it does not exist.
88 * @param mixed $casToken [optional]
89 * @return mixed Returns false on failure
91 abstract public function get( $key, &$casToken = null );
97 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
98 * @return bool Success
100 abstract public function set( $key, $value, $exptime = 0 );
105 * @return bool True if the item was deleted or not found, false on failure
107 abstract public function delete( $key );
110 * Merge changes into the existing cache value (possibly creating a new one).
111 * The callback function returns the new value given the current value
112 * (which will be false if not present), and takes the arguments:
113 * (this BagOStuff, cache key, current value).
116 * @param callable $callback Callback method to be executed
117 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
118 * @param int $attempts The amount of times to attempt a merge in case of failure
119 * @return bool Success
120 * @throws InvalidArgumentException
122 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
123 if ( !is_callable( $callback ) ) {
124 throw new InvalidArgumentException( "Got invalid callback." );
127 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
131 * @see BagOStuff::merge()
134 * @param callable $callback Callback method to be executed
135 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
136 * @param int $attempts The amount of times to attempt a merge in case of failure
137 * @return bool Success
139 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
141 $casToken = null; // passed by reference
142 $currentValue = $this->get( $key, $casToken );
143 // Derive the new value from the old value
144 $value = call_user_func( $callback, $this, $key, $currentValue );
146 if ( $value === false ) {
147 $success = true; // do nothing
148 } elseif ( $currentValue === false ) {
149 // Try to create the key, failing if it gets created in the meantime
150 $success = $this->add( $key, $value, $exptime );
152 // Try to update the key, failing if it gets changed in the meantime
153 $success = $this->cas( $casToken, $key, $value, $exptime );
155 } while ( !$success && --$attempts );
161 * Check and set an item
163 * @param mixed $casToken
165 * @param mixed $value
166 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
167 * @return bool Success
170 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
171 throw new Exception( "CAS is not implemented in " . __CLASS__
);
175 * @see BagOStuff::merge()
178 * @param callable $callback Callback method to be executed
179 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
180 * @param int $attempts The amount of times to attempt a merge in case of failure
181 * @return bool Success
183 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
184 if ( !$this->lock( $key, 6 ) ) {
188 $currentValue = $this->get( $key );
189 // Derive the new value from the old value
190 $value = call_user_func( $callback, $this, $key, $currentValue );
192 if ( $value === false ) {
193 $success = true; // do nothing
195 $success = $this->set( $key, $value, $exptime ); // set the new value
198 if ( !$this->unlock( $key ) ) {
199 // this should never happen
200 trigger_error( "Could not release lock for key '$key'." );
208 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
209 * @param int $expiry Lock expiry [optional]
210 * @return bool Success
212 public function lock( $key, $timeout = 6, $expiry = 6 ) {
213 $this->clearLastError();
214 $timestamp = microtime( true ); // starting UNIX timestamp
215 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
217 } elseif ( $this->getLastError() ) {
221 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
222 $sleep = 2 * $uRTT; // rough time to do get()+set()
224 $locked = false; // lock acquired
225 $attempts = 0; // failed attempts
227 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
228 // Exponentially back off after failed attempts to avoid network spam.
229 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
232 usleep( $sleep ); // back off
233 $this->clearLastError();
234 $locked = $this->add( "{$key}:lock", 1, $expiry );
235 if ( $this->getLastError() ) {
238 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
245 * @return bool Success
247 public function unlock( $key ) {
248 return $this->delete( "{$key}:lock" );
252 * Delete all objects expiring before a certain date.
253 * @param string $date The reference date in MW format
254 * @param callable|bool $progressCallback Optional, a function which will be called
255 * regularly during long-running operations with the percentage progress
256 * as the first parameter.
258 * @return bool Success, false if unimplemented
260 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
265 /* *** Emulated functions *** */
268 * Get an associative array containing the item for each of the keys that have items.
269 * @param array $keys List of strings
272 public function getMulti( array $keys ) {
274 foreach ( $keys as $key ) {
275 $val = $this->get( $key );
276 if ( $val !== false ) {
285 * @param array $data $key => $value assoc array
286 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
287 * @return bool Success
290 public function setMulti( array $data, $exptime = 0 ) {
292 foreach ( $data as $key => $value ) {
293 if ( !$this->set( $key, $value, $exptime ) ) {
302 * @param mixed $value
303 * @param int $exptime
304 * @return bool Success
306 public function add( $key, $value, $exptime = 0 ) {
307 if ( $this->get( $key ) === false ) {
308 return $this->set( $key, $value, $exptime );
310 return false; // key already set
314 * Increase stored value of $key by $value while preserving its TTL
315 * @param string $key Key to increase
316 * @param int $value Value to add to $key (Default 1)
317 * @return int|bool New value or false on failure
319 public function incr( $key, $value = 1 ) {
320 if ( !$this->lock( $key ) ) {
323 $n = $this->get( $key );
324 if ( $this->isInteger( $n ) ) { // key exists?
325 $n +
= intval( $value );
326 $this->set( $key, max( 0, $n ) ); // exptime?
330 $this->unlock( $key );
336 * Decrease stored value of $key by $value while preserving its TTL
339 * @return int|bool New value or false on failure
341 public function decr( $key, $value = 1 ) {
342 return $this->incr( $key, - $value );
346 * Increase stored value of $key by $value while preserving its TTL
348 * This will create the key with value $init and TTL $ttl if not present
357 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
358 return $this->incr( $key, $value ) ||
359 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
363 * Get the "last error" registered; clearLastError() should be called manually
364 * @return int ERR_* constant for the "last error" registry
367 public function getLastError() {
368 return $this->lastError
;
372 * Clear the "last error" registry
375 public function clearLastError() {
376 $this->lastError
= self
::ERR_NONE
;
380 * Set the "last error" registry
381 * @param int $err ERR_* constant
384 protected function setLastError( $err ) {
385 $this->lastError
= $err;
389 * Modify a cache update operation array for EventRelayer::notify()
391 * This is used for relayed writes, e.g. for broadcasting a change
392 * to multiple data-centers. If the array contains a 'val' field
393 * then the command involves setting a key to that value. Note that
394 * for simplicity, 'val' is always a simple scalar value. This method
395 * is used to possibly serialize the value and add any cache-specific
396 * key/values needed for the relayer daemon (e.g. memcached flags).
398 * @param array $event
402 public function modifySimpleRelayEvent( array $event ) {
407 * @param string $text
409 protected function debug( $text ) {
410 if ( $this->debugMode
) {
411 $this->logger
->debug( "{class} debug: $text", array(
412 'class' => get_class( $this ),
418 * Convert an optionally relative time to an absolute time
419 * @param int $exptime
422 protected function convertExpiry( $exptime ) {
423 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
424 return time() +
$exptime;
431 * Convert an optionally absolute expiry time to a relative time. If an
432 * absolute time is specified which is in the past, use a short expiry time.
434 * @param int $exptime
437 protected function convertToRelative( $exptime ) {
438 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
440 if ( $exptime <= 0 ) {
450 * Check if a value is an integer
452 * @param mixed $value
455 protected function isInteger( $value ) {
456 return ( is_int( $value ) ||
ctype_digit( $value ) );