Merge "Import: Handle uploads with sha1 starting with 0 properly"
[mediawiki.git] / includes / libs / objectcache / BagOStuff.php
blobb9be43df8a70c9e1d2feac9801bdf52edcf16a4b
1 <?php
2 /**
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
21 * @file
22 * @ingroup Cache
25 /**
26 * @defgroup Cache Cache
29 use Psr\Log\LoggerAwareInterface;
30 use Psr\Log\LoggerInterface;
31 use Psr\Log\NullLogger;
33 /**
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:
38 * @code
39 * $bag = new HashBagOStuff();
40 * $bag = new SqlBagOStuff(); # connect to db first
41 * @endcode
43 * @ingroup Cache
45 abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
46 /** @var array[] Lock tracking */
47 protected $locks = array();
49 /** @var integer */
50 protected $lastError = self::ERR_NONE;
52 /** @var string */
53 protected $keyspace = 'local';
55 /** @var LoggerInterface */
56 protected $logger;
58 /** @var bool */
59 private $debugMode = false;
61 /** Possible values for getLastError() */
62 const ERR_NONE = 0; // no error
63 const ERR_NO_RESPONSE = 1; // no response
64 const ERR_UNREACHABLE = 2; // can't connect
65 const ERR_UNEXPECTED = 3; // response gave some error
67 /** Bitfield constants for get()/getMulti() */
68 const READ_LATEST = 1; // use latest data for replicated stores
69 const READ_VERIFIED = 2; // promise that caller can tell when keys are stale
70 /** Bitfield constants for set()/merge() */
71 const WRITE_SYNC = 1; // synchronously write to all locations for replicated stores
73 public function __construct( array $params = array() ) {
74 if ( isset( $params['logger'] ) ) {
75 $this->setLogger( $params['logger'] );
76 } else {
77 $this->setLogger( new NullLogger() );
80 if ( isset( $params['keyspace'] ) ) {
81 $this->keyspace = $params['keyspace'];
85 /**
86 * @param LoggerInterface $logger
87 * @return null
89 public function setLogger( LoggerInterface $logger ) {
90 $this->logger = $logger;
93 /**
94 * @param bool $bool
96 public function setDebug( $bool ) {
97 $this->debugMode = $bool;
101 * Get an item with the given key, regenerating and setting it if not found
103 * If the callback returns false, then nothing is stored.
105 * @param string $key
106 * @param int $ttl Time-to-live (seconds)
107 * @param callable $callback Callback that derives the new value
108 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
109 * @return mixed The cached value if found or the result of $callback otherwise
110 * @since 1.27
112 final public function getWithSetCallback( $key, $ttl, $callback, $flags = 0 ) {
113 $value = $this->get( $key, $flags );
115 if ( $value === false ) {
116 if ( !is_callable( $callback ) ) {
117 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
119 $value = call_user_func( $callback );
120 if ( $value !== false ) {
121 $this->set( $key, $value, $ttl );
125 return $value;
129 * Get an item with the given key
131 * If the key includes a determistic input hash (e.g. the key can only have
132 * the correct value) or complete staleness checks are handled by the caller
133 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
134 * This lets tiered backends know they can safely upgrade a cached value to
135 * higher tiers using standard TTLs.
137 * @param string $key
138 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
139 * @param integer $oldFlags [unused]
140 * @return mixed Returns false on failure and if the item does not exist
142 public function get( $key, $flags = 0, $oldFlags = null ) {
143 // B/C for ( $key, &$casToken = null, $flags = 0 )
144 $flags = is_int( $oldFlags ) ? $oldFlags : $flags;
146 return $this->doGet( $key, $flags );
150 * @param string $key
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 abstract protected function doGet( $key, $flags = 0 );
157 * @note: This method is only needed if merge() uses mergeViaCas()
159 * @param string $key
160 * @param mixed $casToken
161 * @param integer $flags Bitfield of BagOStuff::READ_* constants [optional]
162 * @return mixed Returns false on failure and if the item does not exist
163 * @throws Exception
165 protected function getWithToken( $key, &$casToken, $flags = 0 ) {
166 throw new Exception( __METHOD__ . ' not implemented.' );
170 * Set an item
172 * @param string $key
173 * @param mixed $value
174 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
175 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
176 * @return bool Success
178 abstract public function set( $key, $value, $exptime = 0, $flags = 0 );
181 * Delete an item
183 * @param string $key
184 * @return bool True if the item was deleted or not found, false on failure
186 abstract public function delete( $key );
189 * Merge changes into the existing cache value (possibly creating a new one).
190 * The callback function returns the new value given the current value
191 * (which will be false if not present), and takes the arguments:
192 * (this BagOStuff, cache key, current value).
194 * @param string $key
195 * @param callable $callback Callback method to be executed
196 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
197 * @param int $attempts The amount of times to attempt a merge in case of failure
198 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
199 * @return bool Success
200 * @throws InvalidArgumentException
202 public function merge( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
203 if ( !is_callable( $callback ) ) {
204 throw new InvalidArgumentException( "Got invalid callback." );
207 return $this->mergeViaLock( $key, $callback, $exptime, $attempts, $flags );
211 * @see BagOStuff::merge()
213 * @param string $key
214 * @param callable $callback Callback method to be executed
215 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
216 * @param int $attempts The amount of times to attempt a merge in case of failure
217 * @return bool Success
219 protected function mergeViaCas( $key, $callback, $exptime = 0, $attempts = 10 ) {
220 do {
221 $this->clearLastError();
222 $casToken = null; // passed by reference
223 $currentValue = $this->getWithToken( $key, $casToken, self::READ_LATEST );
224 if ( $this->getLastError() ) {
225 return false; // don't spam retries (retry only on races)
228 // Derive the new value from the old value
229 $value = call_user_func( $callback, $this, $key, $currentValue );
231 $this->clearLastError();
232 if ( $value === false ) {
233 $success = true; // do nothing
234 } elseif ( $currentValue === false ) {
235 // Try to create the key, failing if it gets created in the meantime
236 $success = $this->add( $key, $value, $exptime );
237 } else {
238 // Try to update the key, failing if it gets changed in the meantime
239 $success = $this->cas( $casToken, $key, $value, $exptime );
241 if ( $this->getLastError() ) {
242 return false; // IO error; don't spam retries
244 } while ( !$success && --$attempts );
246 return $success;
250 * Check and set an item
252 * @param mixed $casToken
253 * @param string $key
254 * @param mixed $value
255 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
256 * @return bool Success
257 * @throws Exception
259 protected function cas( $casToken, $key, $value, $exptime = 0 ) {
260 throw new Exception( "CAS is not implemented in " . __CLASS__ );
264 * @see BagOStuff::merge()
266 * @param string $key
267 * @param callable $callback Callback method to be executed
268 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
269 * @param int $attempts The amount of times to attempt a merge in case of failure
270 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
271 * @return bool Success
273 protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
274 if ( !$this->lock( $key, 6 ) ) {
275 return false;
278 $this->clearLastError();
279 $currentValue = $this->get( $key, self::READ_LATEST );
280 if ( $this->getLastError() ) {
281 $success = false;
282 } else {
283 // Derive the new value from the old value
284 $value = call_user_func( $callback, $this, $key, $currentValue );
285 if ( $value === false ) {
286 $success = true; // do nothing
287 } else {
288 $success = $this->set( $key, $value, $exptime, $flags ); // set the new value
292 if ( !$this->unlock( $key ) ) {
293 // this should never happen
294 trigger_error( "Could not release lock for key '$key'." );
297 return $success;
301 * Acquire an advisory lock on a key string
303 * Note that if reentry is enabled, duplicate calls ignore $expiry
305 * @param string $key
306 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
307 * @param int $expiry Lock expiry [optional]; 1 day maximum
308 * @param string $rclass Allow reentry if set and the current lock used this value
309 * @return bool Success
311 public function lock( $key, $timeout = 6, $expiry = 6, $rclass = '' ) {
312 // Avoid deadlocks and allow lock reentry if specified
313 if ( isset( $this->locks[$key] ) ) {
314 if ( $rclass != '' && $this->locks[$key]['class'] === $rclass ) {
315 ++$this->locks[$key]['depth'];
316 return true;
317 } else {
318 return false;
322 $expiry = min( $expiry ?: INF, self::TTL_DAY );
324 $this->clearLastError();
325 $timestamp = microtime( true ); // starting UNIX timestamp
326 if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
327 $locked = true;
328 } elseif ( $this->getLastError() || $timeout <= 0 ) {
329 $locked = false; // network partition or non-blocking
330 } else {
331 // Estimate the RTT (us); use 1ms minimum for sanity
332 $uRTT = max( 1e3, ceil( 1e6 * ( microtime( true ) - $timestamp ) ) );
333 $sleep = 2 * $uRTT; // rough time to do get()+set()
335 $attempts = 0; // failed attempts
336 do {
337 if ( ++$attempts >= 3 && $sleep <= 5e5 ) {
338 // Exponentially back off after failed attempts to avoid network spam.
339 // About 2*$uRTT*(2^n-1) us of "sleep" happen for the next n attempts.
340 $sleep *= 2;
342 usleep( $sleep ); // back off
343 $this->clearLastError();
344 $locked = $this->add( "{$key}:lock", 1, $expiry );
345 if ( $this->getLastError() ) {
346 $locked = false; // network partition
347 break;
349 } while ( !$locked && ( microtime( true ) - $timestamp ) < $timeout );
352 if ( $locked ) {
353 $this->locks[$key] = array( 'class' => $rclass, 'depth' => 1 );
356 return $locked;
360 * Release an advisory lock on a key string
362 * @param string $key
363 * @return bool Success
365 public function unlock( $key ) {
366 if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
367 unset( $this->locks[$key] );
369 return $this->delete( "{$key}:lock" );
372 return true;
376 * Get a lightweight exclusive self-unlocking lock
378 * Note that the same lock cannot be acquired twice.
380 * This is useful for task de-duplication or to avoid obtrusive
381 * (though non-corrupting) DB errors like INSERT key conflicts
382 * or deadlocks when using LOCK IN SHARE MODE.
384 * @param string $key
385 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
386 * @param int $expiry Lock expiry [optional]; 1 day maximum
387 * @param string $rclass Allow reentry if set and the current lock used this value
388 * @return ScopedCallback|null Returns null on failure
389 * @since 1.26
391 final public function getScopedLock( $key, $timeout = 6, $expiry = 30, $rclass = '' ) {
392 $expiry = min( $expiry ?: INF, self::TTL_DAY );
394 if ( !$this->lock( $key, $timeout, $expiry, $rclass ) ) {
395 return null;
398 $lSince = microtime( true ); // lock timestamp
399 // PHP 5.3: Can't use $this in a closure
400 $that = $this;
401 $logger = $this->logger;
403 return new ScopedCallback( function() use ( $that, $logger, $key, $lSince, $expiry ) {
404 $latency = .050; // latency skew (err towards keeping lock present)
405 $age = ( microtime( true ) - $lSince + $latency );
406 if ( ( $age + $latency ) >= $expiry ) {
407 $logger->warning( "Lock for $key held too long ($age sec)." );
408 return; // expired; it's not "safe" to delete the key
410 $that->unlock( $key );
411 } );
415 * Delete all objects expiring before a certain date.
416 * @param string $date The reference date in MW format
417 * @param callable|bool $progressCallback Optional, a function which will be called
418 * regularly during long-running operations with the percentage progress
419 * as the first parameter.
421 * @return bool Success, false if unimplemented
423 public function deleteObjectsExpiringBefore( $date, $progressCallback = false ) {
424 // stub
425 return false;
429 * Get an associative array containing the item for each of the keys that have items.
430 * @param array $keys List of strings
431 * @param integer $flags Bitfield; supports READ_LATEST [optional]
432 * @return array
434 public function getMulti( array $keys, $flags = 0 ) {
435 $res = array();
436 foreach ( $keys as $key ) {
437 $val = $this->get( $key );
438 if ( $val !== false ) {
439 $res[$key] = $val;
442 return $res;
446 * Batch insertion
447 * @param array $data $key => $value assoc array
448 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
449 * @return bool Success
450 * @since 1.24
452 public function setMulti( array $data, $exptime = 0 ) {
453 $res = true;
454 foreach ( $data as $key => $value ) {
455 if ( !$this->set( $key, $value, $exptime ) ) {
456 $res = false;
459 return $res;
463 * @param string $key
464 * @param mixed $value
465 * @param int $exptime
466 * @return bool Success
468 public function add( $key, $value, $exptime = 0 ) {
469 if ( $this->get( $key ) === false ) {
470 return $this->set( $key, $value, $exptime );
472 return false; // key already set
476 * Increase stored value of $key by $value while preserving its TTL
477 * @param string $key Key to increase
478 * @param int $value Value to add to $key (Default 1)
479 * @return int|bool New value or false on failure
481 public function incr( $key, $value = 1 ) {
482 if ( !$this->lock( $key ) ) {
483 return false;
485 $n = $this->get( $key );
486 if ( $this->isInteger( $n ) ) { // key exists?
487 $n += intval( $value );
488 $this->set( $key, max( 0, $n ) ); // exptime?
489 } else {
490 $n = false;
492 $this->unlock( $key );
494 return $n;
498 * Decrease stored value of $key by $value while preserving its TTL
499 * @param string $key
500 * @param int $value
501 * @return int|bool New value or false on failure
503 public function decr( $key, $value = 1 ) {
504 return $this->incr( $key, - $value );
508 * Increase stored value of $key by $value while preserving its TTL
510 * This will create the key with value $init and TTL $ttl instead if not present
512 * @param string $key
513 * @param int $ttl
514 * @param int $value
515 * @param int $init
516 * @return int|bool New value or false on failure
517 * @since 1.24
519 public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
520 $newValue = $this->incr( $key, $value );
521 if ( $newValue === false ) {
522 // No key set; initialize
523 $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
525 if ( $newValue === false ) {
526 // Raced out initializing; increment
527 $newValue = $this->incr( $key, $value );
530 return $newValue;
534 * Get the "last error" registered; clearLastError() should be called manually
535 * @return int ERR_* constant for the "last error" registry
536 * @since 1.23
538 public function getLastError() {
539 return $this->lastError;
543 * Clear the "last error" registry
544 * @since 1.23
546 public function clearLastError() {
547 $this->lastError = self::ERR_NONE;
551 * Set the "last error" registry
552 * @param int $err ERR_* constant
553 * @since 1.23
555 protected function setLastError( $err ) {
556 $this->lastError = $err;
560 * Modify a cache update operation array for EventRelayer::notify()
562 * This is used for relayed writes, e.g. for broadcasting a change
563 * to multiple data-centers. If the array contains a 'val' field
564 * then the command involves setting a key to that value. Note that
565 * for simplicity, 'val' is always a simple scalar value. This method
566 * is used to possibly serialize the value and add any cache-specific
567 * key/values needed for the relayer daemon (e.g. memcached flags).
569 * @param array $event
570 * @return array
571 * @since 1.26
573 public function modifySimpleRelayEvent( array $event ) {
574 return $event;
578 * @param string $text
580 protected function debug( $text ) {
581 if ( $this->debugMode ) {
582 $this->logger->debug( "{class} debug: $text", array(
583 'class' => get_class( $this ),
584 ) );
589 * Convert an optionally relative time to an absolute time
590 * @param int $exptime
591 * @return int
593 protected function convertExpiry( $exptime ) {
594 if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
595 return time() + $exptime;
596 } else {
597 return $exptime;
602 * Convert an optionally absolute expiry time to a relative time. If an
603 * absolute time is specified which is in the past, use a short expiry time.
605 * @param int $exptime
606 * @return int
608 protected function convertToRelative( $exptime ) {
609 if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
610 $exptime -= time();
611 if ( $exptime <= 0 ) {
612 $exptime = 1;
614 return $exptime;
615 } else {
616 return $exptime;
621 * Check if a value is an integer
623 * @param mixed $value
624 * @return bool
626 protected function isInteger( $value ) {
627 return ( is_int( $value ) || ctype_digit( $value ) );
631 * Construct a cache key.
633 * @since 1.27
634 * @param string $keyspace
635 * @param array $args
636 * @return string
638 public function makeKeyInternal( $keyspace, $args ) {
639 $key = $keyspace;
640 foreach ( $args as $arg ) {
641 $arg = str_replace( ':', '%3A', $arg );
642 $key = $key . ':' . $arg;
644 return strtr( $key, ' ', '_' );
648 * Make a global cache key.
650 * @since 1.27
651 * @param string ... Key component (variadic)
652 * @return string
654 public function makeGlobalKey() {
655 return $this->makeKeyInternal( 'global', func_get_args() );
659 * Make a cache key, scoped to this instance's keyspace.
661 * @since 1.27
662 * @param string ... Key component (variadic)
663 * @return string
665 public function makeKey() {
666 return $this->makeKeyInternal( $this->keyspace, func_get_args() );