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;
50 protected $lastError = self
::ERR_NONE
;
53 * @var LoggerInterface
57 /** Possible values for getLastError() */
58 const ERR_NONE
= 0; // no error
59 const ERR_NO_RESPONSE
= 1; // no response
60 const ERR_UNREACHABLE
= 2; // can't connect
61 const ERR_UNEXPECTED
= 3; // response gave some error
63 public function __construct( array $params = array() ) {
64 if ( isset( $params['logger'] ) ) {
65 $this->setLogger( $params['logger'] );
67 $this->setLogger( new NullLogger() );
72 * @param LoggerInterface $logger
75 public function setLogger( LoggerInterface
$logger ) {
76 $this->logger
= $logger;
82 public function setDebug( $bool ) {
83 $this->debugMode
= $bool;
86 /* *** THE GUTS OF THE OPERATION *** */
87 /* Override these with functional things in subclasses */
90 * Get an item with the given key. Returns false if it does not exist.
92 * @param mixed $casToken [optional]
93 * @return mixed Returns false on failure
95 abstract public function get( $key, &$casToken = null );
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 );
107 * Check and set an item.
108 * @param mixed $casToken
110 * @param mixed $value
111 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
112 * @return bool Success
114 abstract public function cas( $casToken, $key, $value, $exptime = 0 );
119 * @param int $time Amount of time to delay the operation (mostly memcached-specific)
120 * @return bool True if the item was deleted or not found, false on failure
122 abstract public function delete( $key, $time = 0 );
125 * Merge changes into the existing cache value (possibly creating a new one).
126 * The callback function returns the new value given the current value (possibly false),
127 * and takes the arguments: (this BagOStuff object, cache key, current value).
130 * @param Closure $callback Callback method to be executed
131 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
132 * @param int $attempts The amount of times to attempt a merge in case of failure
133 * @return bool Success
135 public function merge( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
136 return $this->mergeViaCas( $key, $callback, $exptime, $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 mergeViaCas( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
150 $casToken = null; // passed by reference
151 $currentValue = $this->get( $key, $casToken ); // get the old value
152 $value = $callback( $this, $key, $currentValue ); // derive the new value
154 if ( $value === false ) {
155 $success = true; // do nothing
156 } elseif ( $currentValue === false ) {
157 // Try to create the key, failing if it gets created in the meantime
158 $success = $this->add( $key, $value, $exptime );
160 // Try to update the key, failing if it gets changed in the meantime
161 $success = $this->cas( $casToken, $key, $value, $exptime );
163 } while ( !$success && --$attempts );
169 * @see BagOStuff::merge()
172 * @param Closure $callback Callback method to be executed
173 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
174 * @param int $attempts The amount of times to attempt a merge in case of failure
175 * @return bool Success
177 protected function mergeViaLock( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
178 if ( !$this->lock( $key, 6 ) ) {
182 $currentValue = $this->get( $key ); // get the old value
183 $value = $callback( $this, $key, $currentValue ); // derive the new value
185 if ( $value === false ) {
186 $success = true; // do nothing
188 $success = $this->set( $key, $value, $exptime ); // set the new value
191 if ( !$this->unlock( $key ) ) {
192 // this should never happen
193 trigger_error( "Could not release lock for key '$key'." );
201 * @param int $timeout Lock wait timeout [optional]
202 * @param int $expiry Lock expiry [optional]
203 * @return bool Success
205 public function lock( $key, $timeout = 6, $expiry = 6 ) {
206 $this->clearLastError();
207 $timestamp = microtime( true ); // starting UNIX timestamp
208 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
210 } elseif ( $this->getLastError() ) {
214 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
215 $sleep = 2 * $uRTT; // rough time to do get()+set()
217 $locked = false; // lock acquired
218 $attempts = 0; // failed attempts
220 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
221 // Exponentially back off after failed attempts to avoid network spam.
222 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
225 usleep( $sleep ); // back off
226 $this->clearLastError();
227 $locked = $this->add( "{$key}:lock", 1, $expiry );
228 if ( $this->getLastError() ) {
231 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
238 * @return bool Success
240 public function unlock( $key ) {
241 return $this->delete( "{$key}:lock" );
245 * Delete all objects expiring before a certain date.
246 * @param string $date The reference date in MW format
247 * @param callable|bool $progressCallback Optional, a function which will be called
248 * regularly during long-running operations with the percentage progress
249 * as the first parameter.
251 * @return bool Success, false if unimplemented
253 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
258 /* *** Emulated functions *** */
261 * Get an associative array containing the item for each of the keys that have items.
262 * @param array $keys List of strings
265 public function getMulti( array $keys ) {
267 foreach ( $keys as $key ) {
268 $val = $this->get( $key );
269 if ( $val !== false ) {
278 * @param array $data $key => $value assoc array
279 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
280 * @return bool Success
283 public function setMulti( array $data, $exptime = 0 ) {
285 foreach ( $data as $key => $value ) {
286 if ( !$this->set( $key, $value, $exptime ) ) {
295 * @param mixed $value
296 * @param int $exptime
297 * @return bool Success
299 public function add( $key, $value, $exptime = 0 ) {
300 if ( $this->get( $key ) === false ) {
301 return $this->set( $key, $value, $exptime );
303 return false; // key already set
307 * Increase stored value of $key by $value while preserving its TTL
308 * @param string $key Key to increase
309 * @param int $value Value to add to $key (Default 1)
310 * @return int|bool New value or false on failure
312 public function incr( $key, $value = 1 ) {
313 if ( !$this->lock( $key ) ) {
316 $n = $this->get( $key );
317 if ( $this->isInteger( $n ) ) { // key exists?
318 $n +
= intval( $value );
319 $this->set( $key, max( 0, $n ) ); // exptime?
323 $this->unlock( $key );
329 * Decrease stored value of $key by $value while preserving its TTL
334 public function decr( $key, $value = 1 ) {
335 return $this->incr( $key, - $value );
339 * Increase stored value of $key by $value while preserving its TTL
341 * This will create the key with value $init and TTL $ttl if not present
350 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
351 return $this->incr( $key, $value ) ||
352 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
356 * Get the "last error" registered; clearLastError() should be called manually
357 * @return int ERR_* constant for the "last error" registry
360 public function getLastError() {
361 return $this->lastError
;
365 * Clear the "last error" registry
368 public function clearLastError() {
369 $this->lastError
= self
::ERR_NONE
;
373 * Set the "last error" registry
374 * @param int $err ERR_* constant
377 protected function setLastError( $err ) {
378 $this->lastError
= $err;
382 * @param string $text
384 public function debug( $text ) {
385 if ( $this->debugMode
) {
386 $this->logger
->debug( "{class} debug: $text", array(
387 'class' => get_class( $this ),
393 * Convert an optionally relative time to an absolute time
394 * @param int $exptime
397 protected function convertExpiry( $exptime ) {
398 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
399 return time() +
$exptime;
406 * Convert an optionally absolute expiry time to a relative time. If an
407 * absolute time is specified which is in the past, use a short expiry time.
409 * @param int $exptime
412 protected function convertToRelative( $exptime ) {
413 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
415 if ( $exptime <= 0 ) {
425 * Check if a value is an integer
427 * @param mixed $value
430 protected function isInteger( $value ) {
431 return ( is_int( $value ) ||
ctype_digit( $value ) );