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;
62 * Get an item with the given key. Returns false if it does not exist.
64 * @param mixed $casToken [optional]
65 * @return mixed Returns false on failure
67 abstract public function get( $key, &$casToken = null );
73 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
74 * @return bool Success
76 abstract public function set( $key, $value, $exptime = 0 );
79 * Check and set an item.
80 * @param mixed $casToken
83 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
84 * @return bool Success
86 abstract public function cas( $casToken, $key, $value, $exptime = 0 );
91 * @return bool True if the item was deleted or not found, false on failure
93 abstract public function delete( $key );
96 * Merge changes into the existing cache value (possibly creating a new one).
97 * The callback function returns the new value given the current value (possibly false),
98 * and takes the arguments: (this BagOStuff object, cache key, current value).
101 * @param Closure $callback Callback method to be executed
102 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
103 * @param int $attempts The amount of times to attempt a merge in case of failure
104 * @return bool Success
106 public function merge( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
107 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
111 * @see BagOStuff::merge()
114 * @param Closure $callback Callback method to be executed
115 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
116 * @param int $attempts The amount of times to attempt a merge in case of failure
117 * @return bool Success
119 protected function mergeViaCas( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
121 $casToken = null; // passed by reference
122 $currentValue = $this->get( $key, $casToken ); // get the old value
123 $value = $callback( $this, $key, $currentValue ); // derive the new value
125 if ( $value === false ) {
126 $success = true; // do nothing
127 } elseif ( $currentValue === false ) {
128 // Try to create the key, failing if it gets created in the meantime
129 $success = $this->add( $key, $value, $exptime );
131 // Try to update the key, failing if it gets changed in the meantime
132 $success = $this->cas( $casToken, $key, $value, $exptime );
134 } while ( !$success && --$attempts );
140 * @see BagOStuff::merge()
143 * @param Closure $callback Callback method to be executed
144 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
145 * @param int $attempts The amount of times to attempt a merge in case of failure
146 * @return bool Success
148 protected function mergeViaLock( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
149 if ( !$this->lock( $key, 6 ) ) {
153 $currentValue = $this->get( $key ); // get the old value
154 $value = $callback( $this, $key, $currentValue ); // derive the new value
156 if ( $value === false ) {
157 $success = true; // do nothing
159 $success = $this->set( $key, $value, $exptime ); // set the new value
162 if ( !$this->unlock( $key ) ) {
163 // this should never happen
164 trigger_error( "Could not release lock for key '$key'." );
172 * @param int $timeout Lock wait timeout [optional]
173 * @param int $expiry Lock expiry [optional]
174 * @return bool Success
176 public function lock( $key, $timeout = 6, $expiry = 6 ) {
177 $this->clearLastError();
178 $timestamp = microtime( true ); // starting UNIX timestamp
179 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
181 } elseif ( $this->getLastError() ) {
185 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
186 $sleep = 2 * $uRTT; // rough time to do get()+set()
188 $locked = false; // lock acquired
189 $attempts = 0; // failed attempts
191 if ( ++
$attempts >= 3 && $sleep <= 1e6
) {
192 // Exponentially back off after failed attempts to avoid network spam.
193 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
196 usleep( $sleep ); // back off
197 $this->clearLastError();
198 $locked = $this->add( "{$key}:lock", 1, $expiry );
199 if ( $this->getLastError() ) {
202 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
209 * @return bool Success
211 public function unlock( $key ) {
212 return $this->delete( "{$key}:lock" );
216 * Delete all objects expiring before a certain date.
217 * @param string $date The reference date in MW format
218 * @param callable|bool $progressCallback Optional, a function which will be called
219 * regularly during long-running operations with the percentage progress
220 * as the first parameter.
222 * @return bool Success, false if unimplemented
224 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
229 /* *** Emulated functions *** */
232 * Get an associative array containing the item for each of the keys that have items.
233 * @param array $keys List of strings
236 public function getMulti( array $keys ) {
238 foreach ( $keys as $key ) {
239 $val = $this->get( $key );
240 if ( $val !== false ) {
249 * @param array $data $key => $value assoc array
250 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
251 * @return bool Success
254 public function setMulti( array $data, $exptime = 0 ) {
256 foreach ( $data as $key => $value ) {
257 if ( !$this->set( $key, $value, $exptime ) ) {
266 * @param mixed $value
267 * @param int $exptime
268 * @return bool Success
270 public function add( $key, $value, $exptime = 0 ) {
271 if ( $this->get( $key ) === false ) {
272 return $this->set( $key, $value, $exptime );
274 return false; // key already set
278 * Increase stored value of $key by $value while preserving its TTL
279 * @param string $key Key to increase
280 * @param int $value Value to add to $key (Default 1)
281 * @return int|bool New value or false on failure
283 public function incr( $key, $value = 1 ) {
284 if ( !$this->lock( $key ) ) {
287 $n = $this->get( $key );
288 if ( $this->isInteger( $n ) ) { // key exists?
289 $n +
= intval( $value );
290 $this->set( $key, max( 0, $n ) ); // exptime?
294 $this->unlock( $key );
300 * Decrease stored value of $key by $value while preserving its TTL
305 public function decr( $key, $value = 1 ) {
306 return $this->incr( $key, - $value );
310 * Increase stored value of $key by $value while preserving its TTL
312 * This will create the key with value $init and TTL $ttl if not present
321 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
322 return $this->incr( $key, $value ) ||
323 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
327 * Get the "last error" registered; clearLastError() should be called manually
328 * @return int ERR_* constant for the "last error" registry
331 public function getLastError() {
332 return $this->lastError
;
336 * Clear the "last error" registry
339 public function clearLastError() {
340 $this->lastError
= self
::ERR_NONE
;
344 * Set the "last error" registry
345 * @param int $err ERR_* constant
348 protected function setLastError( $err ) {
349 $this->lastError
= $err;
353 * @param string $text
355 public function debug( $text ) {
356 if ( $this->debugMode
) {
357 $class = get_class( $this );
358 wfDebug( "$class debug: $text\n" );
363 * Convert an optionally relative time to an absolute time
364 * @param int $exptime
367 protected function convertExpiry( $exptime ) {
368 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
369 return time() +
$exptime;
376 * Convert an optionally absolute expiry time to a relative time. If an
377 * absolute time is specified which is in the past, use a short expiry time.
379 * @param int $exptime
382 protected function convertToRelative( $exptime ) {
383 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
385 if ( $exptime <= 0 ) {
395 * Check if a value is an integer
397 * @param mixed $value
400 protected function isInteger( $value ) {
401 return ( is_int( $value ) ||
ctype_digit( $value ) );