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;
87 * Get an item with the given key. Returns false if it does not exist.
89 * @param mixed $casToken [optional]
90 * @return mixed Returns false on failure
92 abstract public function get( $key, &$casToken = null );
98 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
99 * @return bool Success
101 abstract public function set( $key, $value, $exptime = 0 );
106 * @return bool True if the item was deleted or not found, false on failure
108 abstract public function delete( $key );
111 * Merge changes into the existing cache value (possibly creating a new one).
112 * The callback function returns the new value given the current value (possibly false),
113 * and takes the arguments: (this BagOStuff object, cache key, current value).
116 * @param Closure $callback Callback method to be executed
117 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
118 * @param int $attempts The amount of times to attempt a merge in case of failure
119 * @return bool Success
121 public function merge( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
122 return $this->mergeViaCas( $key, $callback, $exptime, $attempts );
126 * @see BagOStuff::merge()
129 * @param Closure $callback Callback method to be executed
130 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
131 * @param int $attempts The amount of times to attempt a merge in case of failure
132 * @return bool Success
134 protected function mergeViaCas( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
136 $casToken = null; // passed by reference
137 $currentValue = $this->get( $key, $casToken ); // get the old value
138 $value = $callback( $this, $key, $currentValue ); // derive the new value
140 if ( $value === false ) {
141 $success = true; // do nothing
142 } elseif ( $currentValue === false ) {
143 // Try to create the key, failing if it gets created in the meantime
144 $success = $this->add( $key, $value, $exptime );
146 // Try to update the key, failing if it gets changed in the meantime
147 $success = $this->cas( $casToken, $key, $value, $exptime );
149 } while ( !$success && --$attempts );
155 * Check and set an item.
156 * @param mixed $casToken
158 * @param mixed $value
159 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
160 * @return bool Success
162 abstract protected function cas( $casToken, $key, $value, $exptime = 0 );
165 * @see BagOStuff::merge()
168 * @param Closure $callback Callback method to be executed
169 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
170 * @param int $attempts The amount of times to attempt a merge in case of failure
171 * @return bool Success
173 protected function mergeViaLock( $key, Closure
$callback, $exptime = 0, $attempts = 10 ) {
174 if ( !$this->lock( $key, 6 ) ) {
178 $currentValue = $this->get( $key ); // get the old value
179 $value = $callback( $this, $key, $currentValue ); // derive the new value
181 if ( $value === false ) {
182 $success = true; // do nothing
184 $success = $this->set( $key, $value, $exptime ); // set the new value
187 if ( !$this->unlock( $key ) ) {
188 // this should never happen
189 trigger_error( "Could not release lock for key '$key'." );
197 * @param int $timeout Lock wait timeout [optional]
198 * @param int $expiry Lock expiry [optional]
199 * @return bool Success
201 public function lock( $key, $timeout = 6, $expiry = 6 ) {
202 $this->clearLastError();
203 $timestamp = microtime( true ); // starting UNIX timestamp
204 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
206 } elseif ( $this->getLastError() ) {
210 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
211 $sleep = 2 * $uRTT; // rough time to do get()+set()
213 $locked = false; // lock acquired
214 $attempts = 0; // failed attempts
216 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
217 // Exponentially back off after failed attempts to avoid network spam.
218 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
221 usleep( $sleep ); // back off
222 $this->clearLastError();
223 $locked = $this->add( "{$key}:lock", 1, $expiry );
224 if ( $this->getLastError() ) {
227 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
234 * @return bool Success
236 public function unlock( $key ) {
237 return $this->delete( "{$key}:lock" );
241 * Delete all objects expiring before a certain date.
242 * @param string $date The reference date in MW format
243 * @param callable|bool $progressCallback Optional, a function which will be called
244 * regularly during long-running operations with the percentage progress
245 * as the first parameter.
247 * @return bool Success, false if unimplemented
249 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
254 /* *** Emulated functions *** */
257 * Get an associative array containing the item for each of the keys that have items.
258 * @param array $keys List of strings
261 public function getMulti( array $keys ) {
263 foreach ( $keys as $key ) {
264 $val = $this->get( $key );
265 if ( $val !== false ) {
274 * @param array $data $key => $value assoc array
275 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
276 * @return bool Success
279 public function setMulti( array $data, $exptime = 0 ) {
281 foreach ( $data as $key => $value ) {
282 if ( !$this->set( $key, $value, $exptime ) ) {
291 * @param mixed $value
292 * @param int $exptime
293 * @return bool Success
295 public function add( $key, $value, $exptime = 0 ) {
296 if ( $this->get( $key ) === false ) {
297 return $this->set( $key, $value, $exptime );
299 return false; // key already set
303 * Increase stored value of $key by $value while preserving its TTL
304 * @param string $key Key to increase
305 * @param int $value Value to add to $key (Default 1)
306 * @return int|bool New value or false on failure
308 public function incr( $key, $value = 1 ) {
309 if ( !$this->lock( $key ) ) {
312 $n = $this->get( $key );
313 if ( $this->isInteger( $n ) ) { // key exists?
314 $n +
= intval( $value );
315 $this->set( $key, max( 0, $n ) ); // exptime?
319 $this->unlock( $key );
325 * Decrease stored value of $key by $value while preserving its TTL
330 public function decr( $key, $value = 1 ) {
331 return $this->incr( $key, - $value );
335 * Increase stored value of $key by $value while preserving its TTL
337 * This will create the key with value $init and TTL $ttl if not present
346 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
347 return $this->incr( $key, $value ) ||
348 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
352 * Get the "last error" registered; clearLastError() should be called manually
353 * @return int ERR_* constant for the "last error" registry
356 public function getLastError() {
357 return $this->lastError
;
361 * Clear the "last error" registry
364 public function clearLastError() {
365 $this->lastError
= self
::ERR_NONE
;
369 * Set the "last error" registry
370 * @param int $err ERR_* constant
373 protected function setLastError( $err ) {
374 $this->lastError
= $err;
378 * @param string $text
380 public function debug( $text ) {
381 if ( $this->debugMode
) {
382 $this->logger
->debug( "{class} debug: $text", array(
383 'class' => get_class( $this ),
389 * Convert an optionally relative time to an absolute time
390 * @param int $exptime
393 protected function convertExpiry( $exptime ) {
394 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
395 return time() +
$exptime;
402 * Convert an optionally absolute expiry time to a relative time. If an
403 * absolute time is specified which is in the past, use a short expiry time.
405 * @param int $exptime
408 protected function convertToRelative( $exptime ) {
409 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
411 if ( $exptime <= 0 ) {
421 * Check if a value is an integer
423 * @param mixed $value
426 protected function isInteger( $value ) {
427 return ( is_int( $value ) ||
ctype_digit( $value ) );