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
122 * @throws InvalidArgumentException
124 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
125 if ( !is_callable( $callback ) ) {
126 throw new InvalidArgumentException( "Got invalid callback." );
129 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
133 * @see BagOStuff::merge()
136 * @param callable $callback Callback method to be executed
137 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
138 * @param int $attempts The amount of times to attempt a merge in case of failure
139 * @return bool Success
141 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
143 $casToken = null; // passed by reference
144 $currentValue = $this->get( $key, $casToken );
145 // Derive the new value from the old value
146 $value = call_user_func( $callback, $this, $key, $currentValue );
148 if ( $value === false ) {
149 $success = true; // do nothing
150 } elseif ( $currentValue === false ) {
151 // Try to create the key, failing if it gets created in the meantime
152 $success = $this->add( $key, $value, $exptime );
154 // Try to update the key, failing if it gets changed in the meantime
155 $success = $this->cas( $casToken, $key, $value, $exptime );
157 } while ( !$success && --$attempts );
163 * Check and set an item
165 * @param mixed $casToken
167 * @param mixed $value
168 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
169 * @return bool Success
172 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
173 throw new Exception( "CAS is not implemented in " . __CLASS__
);
177 * @see BagOStuff::merge()
180 * @param callable $callback Callback method to be executed
181 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
182 * @param int $attempts The amount of times to attempt a merge in case of failure
183 * @return bool Success
185 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
186 if ( !$this->lock( $key, 6 ) ) {
190 $currentValue = $this->get( $key );
191 // Derive the new value from the old value
192 $value = call_user_func( $callback, $this, $key, $currentValue );
194 if ( $value === false ) {
195 $success = true; // do nothing
197 $success = $this->set( $key, $value, $exptime ); // set the new value
200 if ( !$this->unlock( $key ) ) {
201 // this should never happen
202 trigger_error( "Could not release lock for key '$key'." );
210 * @param int $timeout Lock wait timeout [optional]
211 * @param int $expiry Lock expiry [optional]
212 * @return bool Success
214 public function lock( $key, $timeout = 6, $expiry = 6 ) {
215 $this->clearLastError();
216 $timestamp = microtime( true ); // starting UNIX timestamp
217 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
219 } elseif ( $this->getLastError() ) {
223 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
224 $sleep = 2 * $uRTT; // rough time to do get()+set()
226 $locked = false; // lock acquired
227 $attempts = 0; // failed attempts
229 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
230 // Exponentially back off after failed attempts to avoid network spam.
231 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
234 usleep( $sleep ); // back off
235 $this->clearLastError();
236 $locked = $this->add( "{$key}:lock", 1, $expiry );
237 if ( $this->getLastError() ) {
240 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
247 * @return bool Success
249 public function unlock( $key ) {
250 return $this->delete( "{$key}:lock" );
254 * Delete all objects expiring before a certain date.
255 * @param string $date The reference date in MW format
256 * @param callable|bool $progressCallback Optional, a function which will be called
257 * regularly during long-running operations with the percentage progress
258 * as the first parameter.
260 * @return bool Success, false if unimplemented
262 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
267 /* *** Emulated functions *** */
270 * Get an associative array containing the item for each of the keys that have items.
271 * @param array $keys List of strings
274 public function getMulti( array $keys ) {
276 foreach ( $keys as $key ) {
277 $val = $this->get( $key );
278 if ( $val !== false ) {
287 * @param array $data $key => $value assoc array
288 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
289 * @return bool Success
292 public function setMulti( array $data, $exptime = 0 ) {
294 foreach ( $data as $key => $value ) {
295 if ( !$this->set( $key, $value, $exptime ) ) {
304 * @param mixed $value
305 * @param int $exptime
306 * @return bool Success
308 public function add( $key, $value, $exptime = 0 ) {
309 if ( $this->get( $key ) === false ) {
310 return $this->set( $key, $value, $exptime );
312 return false; // key already set
316 * Increase stored value of $key by $value while preserving its TTL
317 * @param string $key Key to increase
318 * @param int $value Value to add to $key (Default 1)
319 * @return int|bool New value or false on failure
321 public function incr( $key, $value = 1 ) {
322 if ( !$this->lock( $key ) ) {
325 $n = $this->get( $key );
326 if ( $this->isInteger( $n ) ) { // key exists?
327 $n +
= intval( $value );
328 $this->set( $key, max( 0, $n ) ); // exptime?
332 $this->unlock( $key );
338 * Decrease stored value of $key by $value while preserving its TTL
341 * @return int|bool New value or false on failure
343 public function decr( $key, $value = 1 ) {
344 return $this->incr( $key, - $value );
348 * Increase stored value of $key by $value while preserving its TTL
350 * This will create the key with value $init and TTL $ttl if not present
359 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
360 return $this->incr( $key, $value ) ||
361 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
365 * Get the "last error" registered; clearLastError() should be called manually
366 * @return int ERR_* constant for the "last error" registry
369 public function getLastError() {
370 return $this->lastError
;
374 * Clear the "last error" registry
377 public function clearLastError() {
378 $this->lastError
= self
::ERR_NONE
;
382 * Set the "last error" registry
383 * @param int $err ERR_* constant
386 protected function setLastError( $err ) {
387 $this->lastError
= $err;
391 * Modify a cache update operation array for EventRelayer::notify()
393 * This is used for relayed writes, e.g. for broadcasting a change
394 * to multiple data-centers. If the array contains a 'val' field
395 * then the command involves setting a key to that value. Note that
396 * for simplicity, 'val' is always a simple scalar value. This method
397 * is used to possibly serialize the value and add any cache-specific
398 * key/values needed for the relayer daemon (e.g. memcached flags).
400 * @param array $event
404 public function modifySimpleRelayEvent( array $event ) {
409 * @param string $text
411 protected function debug( $text ) {
412 if ( $this->debugMode
) {
413 $this->logger
->debug( "{class} debug: $text", array(
414 'class' => get_class( $this ),
420 * Convert an optionally relative time to an absolute time
421 * @param int $exptime
424 protected function convertExpiry( $exptime ) {
425 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
426 return time() +
$exptime;
433 * Convert an optionally absolute expiry time to a relative time. If an
434 * absolute time is specified which is in the past, use a short expiry time.
436 * @param int $exptime
439 protected function convertToRelative( $exptime ) {
440 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
442 if ( $exptime <= 0 ) {
452 * Check if a value is an integer
454 * @param mixed $value
457 protected function isInteger( $value ) {
458 return ( is_int( $value ) ||
ctype_digit( $value ) );