3 * Copyright © 2003-2004 Brion Vibber <brion@pobox.com>
4 * https://www.mediawiki.org/
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
26 * @defgroup Cache Cache
29 use Psr\Log\LoggerAwareInterface
;
30 use Psr\Log\LoggerInterface
;
31 use Psr\Log\NullLogger
;
34 * interface is intended to be more or less compatible with
35 * the PHP memcached client.
37 * backends for local hash array and SQL table included:
39 * $bag = new HashBagOStuff();
40 * $bag = new SqlBagOStuff(); # connect to db first
45 abstract class BagOStuff
implements LoggerAwareInterface
{
46 /** @var array[] Lock tracking */
47 protected $locks = array();
49 protected $lastError = self
::ERR_NONE
;
51 /** @var LoggerInterface */
55 private $debugMode = false;
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 /** Bitfield constants for get()/getMulti() */
64 const READ_LATEST
= 1; // use latest data for replicated stores
65 const READ_VERIFIED
= 2; // promise that caller can tell when keys are stale
67 public function __construct( array $params = array() ) {
68 if ( isset( $params['logger'] ) ) {
69 $this->setLogger( $params['logger'] );
71 $this->setLogger( new NullLogger() );
76 * @param LoggerInterface $logger
79 public function setLogger( LoggerInterface
$logger ) {
80 $this->logger
= $logger;
86 public function setDebug( $bool ) {
87 $this->debugMode
= $bool;
91 * Get an item with the given key
93 * If the key includes a determistic input hash (e.g. the key can only have
94 * the correct value) or complete staleness checks are handled by the caller
95 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
96 * This lets tiered backends know they can safely upgrade a cached value to
97 * higher tiers using standard TTLs.
100 * @param mixed $casToken [optional]
101 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
102 * @return mixed Returns false on failure and if the item does not exist
104 abstract public function get( $key, &$casToken = null, $flags = 0 );
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 set( $key, $value, $exptime = 0 );
120 * @return bool True if the item was deleted or not found, false on failure
122 abstract public function delete( $key );
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
127 * (which will be false if not present), and takes the arguments:
128 * (this BagOStuff, cache key, current value).
131 * @param callable $callback Callback method to be executed
132 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
133 * @param int $attempts The amount of times to attempt a merge in case of failure
134 * @return bool Success
135 * @throws InvalidArgumentException
137 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
138 if ( !is_callable( $callback ) ) {
139 throw new InvalidArgumentException( "Got invalid callback." );
142 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
146 * @see BagOStuff::merge()
149 * @param callable $callback Callback method to be executed
150 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
151 * @param int $attempts The amount of times to attempt a merge in case of failure
152 * @return bool Success
154 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
156 $this->clearLastError();
157 $casToken = null; // passed by reference
158 $currentValue = $this->get( $key, $casToken );
159 if ( $this->getLastError() ) {
160 return false; // don't spam retries (retry only on races)
163 // Derive the new value from the old value
164 $value = call_user_func( $callback, $this, $key, $currentValue );
166 $this->clearLastError();
167 if ( $value === false ) {
168 $success = true; // do nothing
169 } elseif ( $currentValue === false ) {
170 // Try to create the key, failing if it gets created in the meantime
171 $success = $this->add( $key, $value, $exptime );
173 // Try to update the key, failing if it gets changed in the meantime
174 $success = $this->cas( $casToken, $key, $value, $exptime );
176 if ( $this->getLastError() ) {
177 return false; // IO error; don't spam retries
179 } while ( !$success && --$attempts );
185 * Check and set an item
187 * @param mixed $casToken
189 * @param mixed $value
190 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
191 * @return bool Success
194 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
195 throw new Exception( "CAS is not implemented in " . __CLASS__
);
199 * @see BagOStuff::merge()
202 * @param callable $callback Callback method to be executed
203 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
204 * @param int $attempts The amount of times to attempt a merge in case of failure
205 * @return bool Success
207 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
208 if ( !$this->lock( $key, 6 ) ) {
212 $this->clearLastError();
213 $currentValue = $this->get( $key );
214 if ( $this->getLastError() ) {
217 // Derive the new value from the old value
218 $value = call_user_func( $callback, $this, $key, $currentValue );
219 if ( $value === false ) {
220 $success = true; // do nothing
222 $success = $this->set( $key, $value, $exptime ); // set the new value
226 if ( !$this->unlock( $key ) ) {
227 // this should never happen
228 trigger_error( "Could not release lock for key '$key'." );
235 * Acquire an advisory lock on a key string
237 * Note that if reentry is enabled, duplicate calls ignore $expiry
240 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
241 * @param int $expiry Lock expiry [optional]; 1 day maximum
242 * @param string $rclass Allow reentry if set and the current lock used this value
243 * @return bool Success
245 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
246 // Avoid deadlocks and allow lock reentry if specified
247 if ( isset( $this->locks
[$key] ) ) {
248 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
249 ++
$this->locks
[$key]['depth'];
256 $expiry = min( $expiry ?
: INF
, 86400 );
258 $this->clearLastError();
259 $timestamp = microtime( true ); // starting UNIX timestamp
260 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
262 } elseif ( $this->getLastError() ||
$timeout <= 0 ) {
263 $locked = false; // network partition or non-blocking
265 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
266 $sleep = 2 * $uRTT; // rough time to do get()+set()
268 $attempts = 0; // failed attempts
270 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
271 // Exponentially back off after failed attempts to avoid network spam.
272 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
275 usleep( $sleep ); // back off
276 $this->clearLastError();
277 $locked = $this->add( "{$key}:lock", 1, $expiry );
278 if ( $this->getLastError() ) {
279 $locked = false; // network partition
282 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
286 $this->locks
[$key] = array( 'class' => $rclass, 'depth' => 1 );
293 * Release an advisory lock on a key string
296 * @return bool Success
298 public function unlock( $key ) {
299 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
300 unset( $this->locks
[$key] );
302 return $this->delete( "{$key}:lock" );
309 * Get a lightweight exclusive self-unlocking lock
311 * Note that the same lock cannot be acquired twice.
313 * This is useful for task de-duplication or to avoid obtrusive
314 * (though non-corrupting) DB errors like INSERT key conflicts
315 * or deadlocks when using LOCK IN SHARE MODE.
318 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
319 * @param int $expiry Lock expiry [optional]; 1 day maximum
320 * @param string $rclass Allow reentry if set and the current lock used this value
321 * @return ScopedCallback|null Returns null on failure
324 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
325 $expiry = min( $expiry ?
: INF
, 86400 );
327 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
331 $lSince = microtime( true ); // lock timestamp
332 // PHP 5.3: Can't use $this in a closure
334 $logger = $this->logger
;
336 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
337 $latency = .050; // latency skew (err towards keeping lock present)
338 $age = ( microtime( true ) - $lSince +
$latency );
339 if ( ( $age +
$latency ) >= $expiry ) {
340 $logger->warning( "Lock for $key held too long ($age sec)." );
341 return; // expired; it's not "safe" to delete the key
343 $that->unlock( $key );
348 * Delete all objects expiring before a certain date.
349 * @param string $date The reference date in MW format
350 * @param callable|bool $progressCallback Optional, a function which will be called
351 * regularly during long-running operations with the percentage progress
352 * as the first parameter.
354 * @return bool Success, false if unimplemented
356 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
362 * Get an associative array containing the item for each of the keys that have items.
363 * @param array $keys List of strings
364 * @param integer $flags Bitfield; supports READ_LATEST [optional]
367 public function getMulti( array $keys, $flags = 0 ) {
369 foreach ( $keys as $key ) {
370 $val = $this->get( $key );
371 if ( $val !== false ) {
380 * @param array $data $key => $value assoc array
381 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
382 * @return bool Success
385 public function setMulti( array $data, $exptime = 0 ) {
387 foreach ( $data as $key => $value ) {
388 if ( !$this->set( $key, $value, $exptime ) ) {
397 * @param mixed $value
398 * @param int $exptime
399 * @return bool Success
401 public function add( $key, $value, $exptime = 0 ) {
402 if ( $this->get( $key ) === false ) {
403 return $this->set( $key, $value, $exptime );
405 return false; // key already set
409 * Increase stored value of $key by $value while preserving its TTL
410 * @param string $key Key to increase
411 * @param int $value Value to add to $key (Default 1)
412 * @return int|bool New value or false on failure
414 public function incr( $key, $value = 1 ) {
415 if ( !$this->lock( $key ) ) {
418 $n = $this->get( $key );
419 if ( $this->isInteger( $n ) ) { // key exists?
420 $n +
= intval( $value );
421 $this->set( $key, max( 0, $n ) ); // exptime?
425 $this->unlock( $key );
431 * Decrease stored value of $key by $value while preserving its TTL
434 * @return int|bool New value or false on failure
436 public function decr( $key, $value = 1 ) {
437 return $this->incr( $key, - $value );
441 * Increase stored value of $key by $value while preserving its TTL
443 * This will create the key with value $init and TTL $ttl if not present
452 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
453 return $this->incr( $key, $value ) ||
454 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
458 * Get the "last error" registered; clearLastError() should be called manually
459 * @return int ERR_* constant for the "last error" registry
462 public function getLastError() {
463 return $this->lastError
;
467 * Clear the "last error" registry
470 public function clearLastError() {
471 $this->lastError
= self
::ERR_NONE
;
475 * Set the "last error" registry
476 * @param int $err ERR_* constant
479 protected function setLastError( $err ) {
480 $this->lastError
= $err;
484 * Modify a cache update operation array for EventRelayer::notify()
486 * This is used for relayed writes, e.g. for broadcasting a change
487 * to multiple data-centers. If the array contains a 'val' field
488 * then the command involves setting a key to that value. Note that
489 * for simplicity, 'val' is always a simple scalar value. This method
490 * is used to possibly serialize the value and add any cache-specific
491 * key/values needed for the relayer daemon (e.g. memcached flags).
493 * @param array $event
497 public function modifySimpleRelayEvent( array $event ) {
502 * @param string $text
504 protected function debug( $text ) {
505 if ( $this->debugMode
) {
506 $this->logger
->debug( "{class} debug: $text", array(
507 'class' => get_class( $this ),
513 * Convert an optionally relative time to an absolute time
514 * @param int $exptime
517 protected function convertExpiry( $exptime ) {
518 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
519 return time() +
$exptime;
526 * Convert an optionally absolute expiry time to a relative time. If an
527 * absolute time is specified which is in the past, use a short expiry time.
529 * @param int $exptime
532 protected function convertToRelative( $exptime ) {
533 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
535 if ( $exptime <= 0 ) {
545 * Check if a value is an integer
547 * @param mixed $value
550 protected function isInteger( $value ) {
551 return ( is_int( $value ) ||
ctype_digit( $value ) );