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 /** Bitfield constants for get()/getMulti() */
63 const READ_LATEST
= 1; // use latest data for replicated stores
65 public function __construct( array $params = array() ) {
66 if ( isset( $params['logger'] ) ) {
67 $this->setLogger( $params['logger'] );
69 $this->setLogger( new NullLogger() );
74 * @param LoggerInterface $logger
77 public function setLogger( LoggerInterface
$logger ) {
78 $this->logger
= $logger;
84 public function setDebug( $bool ) {
85 $this->debugMode
= $bool;
89 * Get an item with the given key. Returns false if it does not exist.
91 * @param mixed $casToken [optional]
92 * @param integer $flags Bitfield; supports READ_LATEST [optional]
93 * @return mixed Returns false on failure
95 abstract public function get( $key, &$casToken = null, $flags = 0 );
100 * @param mixed $value
101 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
102 * @return bool Success
104 abstract public function set( $key, $value, $exptime = 0 );
109 * @return bool True if the item was deleted or not found, false on failure
111 abstract public function delete( $key );
114 * Merge changes into the existing cache value (possibly creating a new one).
115 * The callback function returns the new value given the current value
116 * (which will be false if not present), and takes the arguments:
117 * (this BagOStuff, cache key, current value).
120 * @param callable $callback Callback method to be executed
121 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
122 * @param int $attempts The amount of times to attempt a merge in case of failure
123 * @return bool Success
124 * @throws InvalidArgumentException
126 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
127 if ( !is_callable( $callback ) ) {
128 throw new InvalidArgumentException( "Got invalid callback." );
131 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
135 * @see BagOStuff::merge()
138 * @param callable $callback Callback method to be executed
139 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
140 * @param int $attempts The amount of times to attempt a merge in case of failure
141 * @return bool Success
143 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
145 $this->clearLastError();
146 $casToken = null; // passed by reference
147 $currentValue = $this->get( $key, $casToken );
148 if ( $this->getLastError() ) {
149 return false; // don't spam retries (retry only on races)
152 // Derive the new value from the old value
153 $value = call_user_func( $callback, $this, $key, $currentValue );
155 $this->clearLastError();
156 if ( $value === false ) {
157 $success = true; // do nothing
158 } elseif ( $currentValue === false ) {
159 // Try to create the key, failing if it gets created in the meantime
160 $success = $this->add( $key, $value, $exptime );
162 // Try to update the key, failing if it gets changed in the meantime
163 $success = $this->cas( $casToken, $key, $value, $exptime );
165 if ( $this->getLastError() ) {
166 return false; // IO error; don't spam retries
168 } while ( !$success && --$attempts );
174 * Check and set an item
176 * @param mixed $casToken
178 * @param mixed $value
179 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
180 * @return bool Success
183 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
184 throw new Exception( "CAS is not implemented in " . __CLASS__
);
188 * @see BagOStuff::merge()
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
196 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
197 if ( !$this->lock( $key, 6 ) ) {
201 $this->clearLastError();
202 $currentValue = $this->get( $key );
203 if ( !$this->getLastError() ) {
204 // Derive the new value from the old value
205 $value = call_user_func( $callback, $this, $key, $currentValue );
207 if ( $value === false ) {
208 $success = true; // do nothing
210 $success = $this->set( $key, $value, $exptime ); // set the new value
214 if ( !$this->unlock( $key ) ) {
215 // this should never happen
216 trigger_error( "Could not release lock for key '$key'." );
224 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
225 * @param int $expiry Lock expiry [optional]
226 * @return bool Success
228 public function lock( $key, $timeout = 6, $expiry = 6 ) {
229 $this->clearLastError();
230 $timestamp = microtime( true ); // starting UNIX timestamp
231 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
233 } elseif ( $this->getLastError() ) {
237 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
238 $sleep = 2 * $uRTT; // rough time to do get()+set()
240 $locked = false; // lock acquired
241 $attempts = 0; // failed attempts
243 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
244 // Exponentially back off after failed attempts to avoid network spam.
245 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
248 usleep( $sleep ); // back off
249 $this->clearLastError();
250 $locked = $this->add( "{$key}:lock", 1, $expiry );
251 if ( $this->getLastError() ) {
254 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
261 * @return bool Success
263 public function unlock( $key ) {
264 return $this->delete( "{$key}:lock" );
268 * Delete all objects expiring before a certain date.
269 * @param string $date The reference date in MW format
270 * @param callable|bool $progressCallback Optional, a function which will be called
271 * regularly during long-running operations with the percentage progress
272 * as the first parameter.
274 * @return bool Success, false if unimplemented
276 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
282 * Get an associative array containing the item for each of the keys that have items.
283 * @param array $keys List of strings
284 * @param integer $flags Bitfield; supports READ_LATEST [optional]
287 public function getMulti( array $keys, $flags = 0 ) {
289 foreach ( $keys as $key ) {
290 $val = $this->get( $key );
291 if ( $val !== false ) {
300 * @param array $data $key => $value assoc array
301 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
302 * @return bool Success
305 public function setMulti( array $data, $exptime = 0 ) {
307 foreach ( $data as $key => $value ) {
308 if ( !$this->set( $key, $value, $exptime ) ) {
317 * @param mixed $value
318 * @param int $exptime
319 * @return bool Success
321 public function add( $key, $value, $exptime = 0 ) {
322 if ( $this->get( $key ) === false ) {
323 return $this->set( $key, $value, $exptime );
325 return false; // key already set
329 * Increase stored value of $key by $value while preserving its TTL
330 * @param string $key Key to increase
331 * @param int $value Value to add to $key (Default 1)
332 * @return int|bool New value or false on failure
334 public function incr( $key, $value = 1 ) {
335 if ( !$this->lock( $key ) ) {
338 $n = $this->get( $key );
339 if ( $this->isInteger( $n ) ) { // key exists?
340 $n +
= intval( $value );
341 $this->set( $key, max( 0, $n ) ); // exptime?
345 $this->unlock( $key );
351 * Decrease stored value of $key by $value while preserving its TTL
354 * @return int|bool New value or false on failure
356 public function decr( $key, $value = 1 ) {
357 return $this->incr( $key, - $value );
361 * Increase stored value of $key by $value while preserving its TTL
363 * This will create the key with value $init and TTL $ttl if not present
372 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
373 return $this->incr( $key, $value ) ||
374 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
378 * Get the "last error" registered; clearLastError() should be called manually
379 * @return int ERR_* constant for the "last error" registry
382 public function getLastError() {
383 return $this->lastError
;
387 * Clear the "last error" registry
390 public function clearLastError() {
391 $this->lastError
= self
::ERR_NONE
;
395 * Set the "last error" registry
396 * @param int $err ERR_* constant
399 protected function setLastError( $err ) {
400 $this->lastError
= $err;
404 * Modify a cache update operation array for EventRelayer::notify()
406 * This is used for relayed writes, e.g. for broadcasting a change
407 * to multiple data-centers. If the array contains a 'val' field
408 * then the command involves setting a key to that value. Note that
409 * for simplicity, 'val' is always a simple scalar value. This method
410 * is used to possibly serialize the value and add any cache-specific
411 * key/values needed for the relayer daemon (e.g. memcached flags).
413 * @param array $event
417 public function modifySimpleRelayEvent( array $event ) {
422 * @param string $text
424 protected function debug( $text ) {
425 if ( $this->debugMode
) {
426 $this->logger
->debug( "{class} debug: $text", array(
427 'class' => get_class( $this ),
433 * Convert an optionally relative time to an absolute time
434 * @param int $exptime
437 protected function convertExpiry( $exptime ) {
438 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
439 return time() +
$exptime;
446 * Convert an optionally absolute expiry time to a relative time. If an
447 * absolute time is specified which is in the past, use a short expiry time.
449 * @param int $exptime
452 protected function convertToRelative( $exptime ) {
453 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
455 if ( $exptime <= 0 ) {
465 * Check if a value is an integer
467 * @param mixed $value
470 protected function isInteger( $value ) {
471 return ( is_int( $value ) ||
ctype_digit( $value ) );