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
32 * interface is intended to be more or less compatible with
33 * the PHP memcached client.
35 * backends for local hash array and SQL table included:
37 * $bag = new HashBagOStuff();
38 * $bag = new SqlBagOStuff(); # connect to db first
43 abstract class BagOStuff
{
44 private $debugMode = false;
46 protected $lastError = self
::ERR_NONE
;
48 /** Possible values for getLastError() */
49 const ERR_NONE
= 0; // no error
50 const ERR_NO_RESPONSE
= 1; // no response
51 const ERR_UNREACHABLE
= 2; // can't connect
52 const ERR_UNEXPECTED
= 3; // response gave some error
57 public function setDebug( $bool ) {
58 $this->debugMode
= $bool;
61 /* *** THE GUTS OF THE OPERATION *** */
62 /* Override these with functional things in subclasses */
65 * Get an item with the given key. Returns false if it does not exist.
67 * @param $casToken[optional] mixed
68 * @return mixed Returns false on failure
70 abstract public function get( $key, &$casToken = null );
76 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
77 * @return bool success
79 abstract public function set( $key, $value, $exptime = 0 );
82 * Check and set an item.
83 * @param $casToken mixed
86 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
87 * @return bool success
89 abstract public function cas( $casToken, $key, $value, $exptime = 0 );
94 * @param int $time Amount of time to delay the operation (mostly memcached-specific)
95 * @return bool True if the item was deleted or not found, false on failure
97 abstract public function delete( $key, $time = 0 );
100 * Merge changes into the existing cache value (possibly creating a new one).
101 * The callback function returns the new value given the current value (possibly false),
102 * and takes the arguments: (this BagOStuff object, cache key, current value).
105 * @param $callback closure Callback method to be executed
106 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
107 * @param int $attempts The amount of times to attempt a merge in case of failure
108 * @return bool success
110 public function merge( $key, closure
$callback, $exptime = 0, $attempts = 10 ) {
111 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
115 * @see BagOStuff::merge()
118 * @param $callback closure 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 protected function mergeViaCas( $key, closure
$callback, $exptime = 0, $attempts = 10 ) {
125 $casToken = null; // passed by reference
126 $currentValue = $this->get( $key, $casToken ); // get the old value
127 $value = $callback( $this, $key, $currentValue ); // derive the new value
129 if ( $value === false ) {
130 $success = true; // do nothing
131 } elseif ( $currentValue === false ) {
132 // Try to create the key, failing if it gets created in the meantime
133 $success = $this->add( $key, $value, $exptime );
135 // Try to update the key, failing if it gets changed in the meantime
136 $success = $this->cas( $casToken, $key, $value, $exptime );
138 } while ( !$success && --$attempts );
144 * @see BagOStuff::merge()
147 * @param $callback closure Callback method to be executed
148 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
149 * @param int $attempts The amount of times to attempt a merge in case of failure
150 * @return bool success
152 protected function mergeViaLock( $key, closure
$callback, $exptime = 0, $attempts = 10 ) {
153 if ( !$this->lock( $key, 6 ) ) {
157 $currentValue = $this->get( $key ); // get the old value
158 $value = $callback( $this, $key, $currentValue ); // derive the new value
160 if ( $value === false ) {
161 $success = true; // do nothing
163 $success = $this->set( $key, $value, $exptime ); // set the new value
166 if ( !$this->unlock( $key ) ) {
167 // this should never happen
168 trigger_error( "Could not release lock for key '$key'." );
176 * @param $timeout integer [optional]
177 * @return bool success
179 public function lock( $key, $timeout = 6 ) {
180 $this->clearLastError();
181 $timestamp = microtime( true ); // starting UNIX timestamp
182 if ( $this->add( "{$key}:lock", 1, $timeout ) ) {
184 } elseif ( $this->getLastError() ) {
188 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
189 $sleep = 2 * $uRTT; // rough time to do get()+set()
191 $locked = false; // lock acquired
192 $attempts = 0; // failed attempts
194 if ( ++
$attempts >= 3 && $sleep <= 1e6
) {
195 // Exponentially back off after failed attempts to avoid network spam.
196 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
199 usleep( $sleep ); // back off
200 $this->clearLastError();
201 $locked = $this->add( "{$key}:lock", 1, $timeout );
202 if ( $this->getLastError() ) {
205 } while ( !$locked );
212 * @return bool success
214 public function unlock( $key ) {
215 return $this->delete( "{$key}:lock" );
219 * Delete all objects expiring before a certain date.
220 * @param string $date The reference date in MW format
221 * @param $progressCallback callback|bool Optional, a function which will be called
222 * regularly during long-running operations with the percentage progress
223 * as the first parameter.
225 * @return bool on success, false if unimplemented
227 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
232 /* *** Emulated functions *** */
235 * Get an associative array containing the item for each of the keys that have items.
236 * @param array $keys List of strings
239 public function getMulti( array $keys ) {
241 foreach ( $keys as $key ) {
242 $val = $this->get( $key );
243 if ( $val !== false ) {
252 * @param $value mixed
253 * @param $exptime integer
254 * @return bool success
256 public function add( $key, $value, $exptime = 0 ) {
257 if ( $this->get( $key ) === false ) {
258 return $this->set( $key, $value, $exptime );
260 return false; // key already set
265 * @param $value mixed
266 * @param $exptime int
267 * @return bool success
270 public function replace( $key, $value, $exptime = 0 ) {
271 wfDeprecated( __METHOD__
, '1.23' );
272 if ( $this->get( $key ) !== false ) {
273 return $this->set( $key, $value, $exptime );
275 return false; // key not already set
279 * Increase stored value of $key by $value while preserving its TTL
280 * @param string $key Key to increase
281 * @param $value Integer: Value to add to $key (Default 1)
282 * @return integer|bool New value or false on failure
284 public function incr( $key, $value = 1 ) {
285 if ( !$this->lock( $key ) ) {
288 $n = $this->get( $key );
289 if ( $this->isInteger( $n ) ) { // key exists?
290 $n +
= intval( $value );
291 $this->set( $key, max( 0, $n ) ); // exptime?
295 $this->unlock( $key );
301 * Decrease stored value of $key by $value while preserving its TTL
303 * @param $value Integer
306 public function decr( $key, $value = 1 ) {
307 return $this->incr( $key, - $value );
311 * Get the "last error" registered; clearLastError() should be called manually
312 * @return integer ERR_* constant for the "last error" registry
315 public function getLastError() {
316 return $this->lastError
;
320 * Clear the "last error" registry
323 public function clearLastError() {
324 $this->lastError
= self
::ERR_NONE
;
328 * Set the "last error" registry
329 * @param $err integer ERR_* constant
332 protected function setLastError( $err ) {
333 $this->lastError
= $err;
337 * @param $text string
339 public function debug( $text ) {
340 if ( $this->debugMode
) {
341 $class = get_class( $this );
342 wfDebug( "$class debug: $text\n" );
347 * Convert an optionally relative time to an absolute time
348 * @param $exptime integer
351 protected function convertExpiry( $exptime ) {
352 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
353 return time() +
$exptime;
360 * Convert an optionally absolute expiry time to a relative time. If an
361 * absolute time is specified which is in the past, use a short expiry time.
363 * @param $exptime integer
366 protected function convertToRelative( $exptime ) {
367 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
369 if ( $exptime <= 0 ) {
379 * Check if a value is an integer
381 * @param $value mixed
384 protected function isInteger( $value ) {
385 return ( is_int( $value ) ||
ctype_digit( $value ) );