3 * Classes to cache objects in PHP accelerators, SQL database or DBA files
5 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
28 * @defgroup Cache Cache
31 use Psr\Log\LoggerAwareInterface
;
32 use Psr\Log\LoggerInterface
;
33 use Psr\Log\NullLogger
;
36 * interface is intended to be more or less compatible with
37 * the PHP memcached client.
39 * backends for local hash array and SQL table included:
41 * $bag = new HashBagOStuff();
42 * $bag = new SqlBagOStuff(); # connect to db first
47 abstract class BagOStuff
implements LoggerAwareInterface
{
48 private $debugMode = false;
51 protected $lastError = self
::ERR_NONE
;
54 * @var LoggerInterface
58 /** Possible values for getLastError() */
59 const ERR_NONE
= 0; // no error
60 const ERR_NO_RESPONSE
= 1; // no response
61 const ERR_UNREACHABLE
= 2; // can't connect
62 const ERR_UNEXPECTED
= 3; // response gave some error
64 public function __construct( array $params = array() ) {
65 if ( isset( $params['logger'] ) ) {
66 $this->setLogger( $params['logger'] );
68 $this->setLogger( new NullLogger() );
73 * @param LoggerInterface $logger
76 public function setLogger( LoggerInterface
$logger ) {
77 $this->logger
= $logger;
83 public function setDebug( $bool ) {
84 $this->debugMode
= $bool;
88 * Get an item with the given key. Returns false if it does not exist.
90 * @param mixed $casToken [optional]
91 * @return mixed Returns false on failure
93 abstract public function get( $key, &$casToken = null );
99 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
100 * @return bool Success
102 abstract public function set( $key, $value, $exptime = 0 );
107 * @return bool True if the item was deleted or not found, false on failure
109 abstract public function delete( $key );
112 * Merge changes into the existing cache value (possibly creating a new one).
113 * The callback function returns the new value given the current value
114 * (which will be false if not present), and takes the arguments:
115 * (this BagOStuff, cache key, current value).
118 * @param callable $callback Callback method to be executed
119 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
120 * @param int $attempts The amount of times to attempt a merge in case of failure
121 * @return bool Success
123 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
124 if ( !is_callable( $callback ) ) {
125 throw new Exception( "Got invalid callback." );
128 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
132 * @see BagOStuff::merge()
135 * @param callable $callback Callback method to be executed
136 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
137 * @param int $attempts The amount of times to attempt a merge in case of failure
138 * @return bool Success
140 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
142 $casToken = null; // passed by reference
143 $currentValue = $this->get( $key, $casToken );
144 // Derive the new value from the old value
145 $value = call_user_func( $callback, $this, $key, $currentValue );
147 if ( $value === false ) {
148 $success = true; // do nothing
149 } elseif ( $currentValue === false ) {
150 // Try to create the key, failing if it gets created in the meantime
151 $success = $this->add( $key, $value, $exptime );
153 // Try to update the key, failing if it gets changed in the meantime
154 $success = $this->cas( $casToken, $key, $value, $exptime );
156 } while ( !$success && --$attempts );
162 * Check and set an item
164 * @param mixed $casToken
166 * @param mixed $value
167 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
168 * @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 [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 * @param string $text
391 protected function debug( $text ) {
392 if ( $this->debugMode
) {
393 $this->logger
->debug( "{class} debug: $text", array(
394 'class' => get_class( $this ),
400 * Convert an optionally relative time to an absolute time
401 * @param int $exptime
404 protected function convertExpiry( $exptime ) {
405 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
406 return time() +
$exptime;
413 * Convert an optionally absolute expiry time to a relative time. If an
414 * absolute time is specified which is in the past, use a short expiry time.
416 * @param int $exptime
419 protected function convertToRelative( $exptime ) {
420 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
422 if ( $exptime <= 0 ) {
432 * Check if a value is an integer
434 * @param mixed $value
437 protected function isInteger( $value ) {
438 return ( is_int( $value ) ||
ctype_digit( $value ) );