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, regenerating and setting it if not found
93 * If the callback returns false, then nothing is stored.
96 * @param int $ttl Time-to-live (seconds)
97 * @param callable $callback Callback that derives the new value
98 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
99 * @return mixed The cached value if found or the result of $callback otherwise
102 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
103 $value = $this->get( $key, $flags );
105 if ( $value === false ) {
106 if ( !is_callable( $callback ) ) {
107 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
109 $value = call_user_func( $callback );
110 if ( $value !== false ) {
111 $this->set( $key, $value, $ttl );
119 * Get an item with the given key
121 * If the key includes a determistic input hash (e.g. the key can only have
122 * the correct value) or complete staleness checks are handled by the caller
123 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
124 * This lets tiered backends know they can safely upgrade a cached value to
125 * higher tiers using standard TTLs.
128 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
129 * @param integer $oldFlags [unused]
130 * @return mixed Returns false on failure and if the item does not exist
132 public function get( $key, $flags = 0, $oldFlags = null ) {
133 // B/C for ( $key, &$casToken = null, $flags = 0 )
134 $flags = is_int( $oldFlags ) ?
$oldFlags : $flags;
136 return $this->doGet( $key, $flags );
141 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
142 * @return mixed Returns false on failure and if the item does not exist
144 abstract protected function doGet( $key, $flags = 0 );
147 * @note: This method is only needed if cas() is not is used for merge()
150 * @param mixed $casToken
151 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
152 * @return mixed Returns false on failure and if the item does not exist
154 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
155 throw new Exception( __METHOD__
. ' not implemented.' );
162 * @param mixed $value
163 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
164 * @return bool Success
166 abstract public function set( $key, $value, $exptime = 0 );
172 * @return bool True if the item was deleted or not found, false on failure
174 abstract public function delete( $key );
177 * Merge changes into the existing cache value (possibly creating a new one).
178 * The callback function returns the new value given the current value
179 * (which will be false if not present), and takes the arguments:
180 * (this BagOStuff, cache key, current value).
183 * @param callable $callback Callback method to be executed
184 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
185 * @param int $attempts The amount of times to attempt a merge in case of failure
186 * @return bool Success
187 * @throws InvalidArgumentException
189 public function merge( $key, $callback, $exptime = 0, $attempts = 10 ) {
190 if ( !is_callable( $callback ) ) {
191 throw new InvalidArgumentException( "Got invalid callback." );
194 return $this->mergeViaLock( $key, $callback, $exptime, $attempts );
198 * @see BagOStuff::merge()
201 * @param callable $callback Callback method to be executed
202 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
203 * @param int $attempts The amount of times to attempt a merge in case of failure
204 * @return bool Success
206 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
208 $this->clearLastError();
209 $casToken = null; // passed by reference
210 $currentValue = $this->getWithToken( $key, $casToken, BagOStuff
::READ_LATEST
);
211 if ( $this->getLastError() ) {
212 return false; // don't spam retries (retry only on races)
215 // Derive the new value from the old value
216 $value = call_user_func( $callback, $this, $key, $currentValue );
218 $this->clearLastError();
219 if ( $value === false ) {
220 $success = true; // do nothing
221 } elseif ( $currentValue === false ) {
222 // Try to create the key, failing if it gets created in the meantime
223 $success = $this->add( $key, $value, $exptime );
225 // Try to update the key, failing if it gets changed in the meantime
226 $success = $this->cas( $casToken, $key, $value, $exptime );
228 if ( $this->getLastError() ) {
229 return false; // IO error; don't spam retries
231 } while ( !$success && --$attempts );
237 * Check and set an item
239 * @param mixed $casToken
241 * @param mixed $value
242 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
243 * @return bool Success
246 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
247 throw new Exception( "CAS is not implemented in " . __CLASS__
);
251 * @see BagOStuff::merge()
254 * @param callable $callback Callback method to be executed
255 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
256 * @param int $attempts The amount of times to attempt a merge in case of failure
257 * @return bool Success
259 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10 ) {
260 if ( !$this->lock( $key, 6 ) ) {
264 $this->clearLastError();
265 $currentValue = $this->get( $key, BagOStuff
::READ_LATEST
);
266 if ( $this->getLastError() ) {
269 // Derive the new value from the old value
270 $value = call_user_func( $callback, $this, $key, $currentValue );
271 if ( $value === false ) {
272 $success = true; // do nothing
274 $success = $this->set( $key, $value, $exptime ); // set the new value
278 if ( !$this->unlock( $key ) ) {
279 // this should never happen
280 trigger_error( "Could not release lock for key '$key'." );
287 * Acquire an advisory lock on a key string
289 * Note that if reentry is enabled, duplicate calls ignore $expiry
292 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
293 * @param int $expiry Lock expiry [optional]; 1 day maximum
294 * @param string $rclass Allow reentry if set and the current lock used this value
295 * @return bool Success
297 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
298 // Avoid deadlocks and allow lock reentry if specified
299 if ( isset( $this->locks
[$key] ) ) {
300 if ( $rclass != '' && $this->locks
[$key]['class'] === $rclass ) {
301 ++
$this->locks
[$key]['depth'];
308 $expiry = min( $expiry ?
: INF
, 86400 );
310 $this->clearLastError();
311 $timestamp = microtime( true ); // starting UNIX timestamp
312 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
314 } elseif ( $this->getLastError() ||
$timeout <= 0 ) {
315 $locked = false; // network partition or non-blocking
317 $uRTT = ceil( 1e6
* ( microtime( true ) - $timestamp ) ); // estimate RTT (us)
318 $sleep = 2 * $uRTT; // rough time to do get()+set()
320 $attempts = 0; // failed attempts
322 if ( ++
$attempts >= 3 && $sleep <= 5e5
) {
323 // Exponentially back off after failed attempts to avoid network spam.
324 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
327 usleep( $sleep ); // back off
328 $this->clearLastError();
329 $locked = $this->add( "{$key}:lock", 1, $expiry );
330 if ( $this->getLastError() ) {
331 $locked = false; // network partition
334 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
338 $this->locks
[$key] = array( 'class' => $rclass, 'depth' => 1 );
345 * Release an advisory lock on a key string
348 * @return bool Success
350 public function unlock( $key ) {
351 if ( isset( $this->locks
[$key] ) && --$this->locks
[$key]['depth'] <= 0 ) {
352 unset( $this->locks
[$key] );
354 return $this->delete( "{$key}:lock" );
361 * Get a lightweight exclusive self-unlocking lock
363 * Note that the same lock cannot be acquired twice.
365 * This is useful for task de-duplication or to avoid obtrusive
366 * (though non-corrupting) DB errors like INSERT key conflicts
367 * or deadlocks when using LOCK IN SHARE MODE.
370 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
371 * @param int $expiry Lock expiry [optional]; 1 day maximum
372 * @param string $rclass Allow reentry if set and the current lock used this value
373 * @return ScopedCallback|null Returns null on failure
376 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
377 $expiry = min( $expiry ?
: INF
, 86400 );
379 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
383 $lSince = microtime( true ); // lock timestamp
384 // PHP 5.3: Can't use $this in a closure
386 $logger = $this->logger
;
388 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
389 $latency = .050; // latency skew (err towards keeping lock present)
390 $age = ( microtime( true ) - $lSince +
$latency );
391 if ( ( $age +
$latency ) >= $expiry ) {
392 $logger->warning( "Lock for $key held too long ($age sec)." );
393 return; // expired; it's not "safe" to delete the key
395 $that->unlock( $key );
400 * Delete all objects expiring before a certain date.
401 * @param string $date The reference date in MW format
402 * @param callable|bool $progressCallback Optional, a function which will be called
403 * regularly during long-running operations with the percentage progress
404 * as the first parameter.
406 * @return bool Success, false if unimplemented
408 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
414 * Get an associative array containing the item for each of the keys that have items.
415 * @param array $keys List of strings
416 * @param integer $flags Bitfield; supports READ_LATEST [optional]
419 public function getMulti( array $keys, $flags = 0 ) {
421 foreach ( $keys as $key ) {
422 $val = $this->get( $key );
423 if ( $val !== false ) {
432 * @param array $data $key => $value assoc array
433 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
434 * @return bool Success
437 public function setMulti( array $data, $exptime = 0 ) {
439 foreach ( $data as $key => $value ) {
440 if ( !$this->set( $key, $value, $exptime ) ) {
449 * @param mixed $value
450 * @param int $exptime
451 * @return bool Success
453 public function add( $key, $value, $exptime = 0 ) {
454 if ( $this->get( $key ) === false ) {
455 return $this->set( $key, $value, $exptime );
457 return false; // key already set
461 * Increase stored value of $key by $value while preserving its TTL
462 * @param string $key Key to increase
463 * @param int $value Value to add to $key (Default 1)
464 * @return int|bool New value or false on failure
466 public function incr( $key, $value = 1 ) {
467 if ( !$this->lock( $key ) ) {
470 $n = $this->get( $key );
471 if ( $this->isInteger( $n ) ) { // key exists?
472 $n +
= intval( $value );
473 $this->set( $key, max( 0, $n ) ); // exptime?
477 $this->unlock( $key );
483 * Decrease stored value of $key by $value while preserving its TTL
486 * @return int|bool New value or false on failure
488 public function decr( $key, $value = 1 ) {
489 return $this->incr( $key, - $value );
493 * Increase stored value of $key by $value while preserving its TTL
495 * This will create the key with value $init and TTL $ttl if not present
504 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
505 return $this->incr( $key, $value ) ||
506 $this->add( $key, (int)$init, $ttl ) ||
$this->incr( $key, $value );
510 * Get the "last error" registered; clearLastError() should be called manually
511 * @return int ERR_* constant for the "last error" registry
514 public function getLastError() {
515 return $this->lastError
;
519 * Clear the "last error" registry
522 public function clearLastError() {
523 $this->lastError
= self
::ERR_NONE
;
527 * Set the "last error" registry
528 * @param int $err ERR_* constant
531 protected function setLastError( $err ) {
532 $this->lastError
= $err;
536 * Modify a cache update operation array for EventRelayer::notify()
538 * This is used for relayed writes, e.g. for broadcasting a change
539 * to multiple data-centers. If the array contains a 'val' field
540 * then the command involves setting a key to that value. Note that
541 * for simplicity, 'val' is always a simple scalar value. This method
542 * is used to possibly serialize the value and add any cache-specific
543 * key/values needed for the relayer daemon (e.g. memcached flags).
545 * @param array $event
549 public function modifySimpleRelayEvent( array $event ) {
554 * @param string $text
556 protected function debug( $text ) {
557 if ( $this->debugMode
) {
558 $this->logger
->debug( "{class} debug: $text", array(
559 'class' => get_class( $this ),
565 * Convert an optionally relative time to an absolute time
566 * @param int $exptime
569 protected function convertExpiry( $exptime ) {
570 if ( ( $exptime != 0 ) && ( $exptime < 86400 * 3650 /* 10 years */ ) ) {
571 return time() +
$exptime;
578 * Convert an optionally absolute expiry time to a relative time. If an
579 * absolute time is specified which is in the past, use a short expiry time.
581 * @param int $exptime
584 protected function convertToRelative( $exptime ) {
585 if ( $exptime >= 86400 * 3650 /* 10 years */ ) {
587 if ( $exptime <= 0 ) {
597 * Check if a value is an integer
599 * @param mixed $value
602 protected function isInteger( $value ) {
603 return ( is_int( $value ) ||
ctype_digit( $value ) );