Update composer/spdx-licenses to 1.4.0 and mediawiki/mediawiki-codesniffer to 21.0.0
[lhc/web/wiklou.git] / includes / libs / objectcache / BagOStuff.php
index 424d986..82ae5ae 100644 (file)
@@ -81,6 +81,9 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
        /** @var callable[] */
        protected $busyCallbacks = [];
 
+       /** @var float|null */
+       private $wallClockOverride;
+
        /** @var int[] Map of (ATTR_* class constant => QOS_* class constant) */
        protected $attrMap = [];
 
@@ -130,7 +133,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
 
        /**
         * @param LoggerInterface $logger
-        * @return null
+        * @return void
         */
        public function setLogger( LoggerInterface $logger ) {
                $this->logger = $logger;
@@ -182,7 +185,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         *
         * @param string $key
         * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
-        * @param int $oldFlags [unused]
+        * @param int|null $oldFlags [unused]
         * @return mixed Returns false on failure and if the item does not exist
         */
        public function get( $key, $flags = 0, $oldFlags = null ) {
@@ -235,7 +238,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
        abstract protected function doGet( $key, $flags = 0 );
 
        /**
-        * @note: This method is only needed if merge() uses mergeViaCas()
+        * @note This method is only needed if merge() uses mergeViaCas()
         *
         * @param string $key
         * @param mixed &$casToken
@@ -305,6 +308,11 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
                        $this->reportDupes = $reportDupes;
 
                        if ( $this->getLastError() ) {
+                               $this->logger->warning(
+                                       __METHOD__ . ' failed due to I/O error on get() for {key}.',
+                                       [ 'key' => $key ]
+                               );
+
                                return false; // don't spam retries (retry only on races)
                        }
 
@@ -322,6 +330,11 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
                                $success = $this->cas( $casToken, $key, $value, $exptime );
                        }
                        if ( $this->getLastError() ) {
+                               $this->logger->warning(
+                                       __METHOD__ . ' failed due to I/O error for {key}.',
+                                       [ 'key' => $key ]
+                               );
+
                                return false; // IO error; don't spam retries
                        }
                } while ( !$success && --$attempts );
@@ -340,7 +353,26 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         * @throws Exception
         */
        protected function cas( $casToken, $key, $value, $exptime = 0 ) {
-               throw new Exception( "CAS is not implemented in " . __CLASS__ );
+               if ( !$this->lock( $key, 0 ) ) {
+                       return false; // non-blocking
+               }
+
+               $curCasToken = null; // passed by reference
+               $this->getWithToken( $key, $curCasToken, self::READ_LATEST );
+               if ( $casToken === $curCasToken ) {
+                       $success = $this->set( $key, $value, $exptime );
+               } else {
+                       $this->logger->info(
+                               __METHOD__ . ' failed due to race condition for {key}.',
+                               [ 'key' => $key ]
+                       );
+
+                       $success = false; // mismatched or failed
+               }
+
+               $this->unlock( $key );
+
+               return $success;
        }
 
        /**
@@ -354,7 +386,13 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         * @return bool Success
         */
        protected function mergeViaLock( $key, $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
-               if ( !$this->lock( $key, 6 ) ) {
+               if ( $attempts <= 1 ) {
+                       $timeout = 0; // clearly intended to be "non-blocking"
+               } else {
+                       $timeout = 3;
+               }
+
+               if ( !$this->lock( $key, $timeout ) ) {
                        return false;
                }
 
@@ -365,6 +403,11 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
                $this->reportDupes = $reportDupes;
 
                if ( $this->getLastError() ) {
+                       $this->logger->warning(
+                               __METHOD__ . ' failed due to I/O error on get() for {key}.',
+                               [ 'key' => $key ]
+                       );
+
                        $success = false;
                } else {
                        // Derive the new value from the old value
@@ -420,13 +463,19 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
                        }
                }
 
+               $fname = __METHOD__;
                $expiry = min( $expiry ?: INF, self::TTL_DAY );
                $loop = new WaitConditionLoop(
-                       function () use ( $key, $timeout, $expiry ) {
+                       function () use ( $key, $timeout, $expiry, $fname ) {
                                $this->clearLastError();
                                if ( $this->add( "{$key}:lock", 1, $expiry ) ) {
                                        return true; // locked!
                                } elseif ( $this->getLastError() ) {
+                                       $this->logger->warning(
+                                               $fname . ' failed due to I/O error for {key}.',
+                                               [ 'key' => $key ]
+                                       );
+
                                        return WaitConditionLoop::CONDITION_ABORTED; // network partition?
                                }
 
@@ -435,9 +484,15 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
                        $timeout
                );
 
-               $locked = ( $loop->invoke() === $loop::CONDITION_REACHED );
+               $code = $loop->invoke();
+               $locked = ( $code === $loop::CONDITION_REACHED );
                if ( $locked ) {
                        $this->locks[$key] = [ 'class' => $rclass, 'depth' => 1 ];
+               } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
+                       $this->logger->warning(
+                               "$fname failed due to timeout for {key}.",
+                               [ 'key' => $key, 'timeout' => $timeout ]
+                       );
                }
 
                return $locked;
@@ -453,7 +508,15 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
                if ( isset( $this->locks[$key] ) && --$this->locks[$key]['depth'] <= 0 ) {
                        unset( $this->locks[$key] );
 
-                       return $this->delete( "{$key}:lock" );
+                       $ok = $this->delete( "{$key}:lock" );
+                       if ( !$ok ) {
+                               $this->logger->warning(
+                                       __METHOD__ . ' failed to release lock for {key}.',
+                                       [ 'key' => $key ]
+                               );
+                       }
+
+                       return $ok;
                }
 
                return true;
@@ -482,13 +545,16 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
                        return null;
                }
 
-               $lSince = microtime( true ); // lock timestamp
+               $lSince = $this->getCurrentTime(); // lock timestamp
 
                return new ScopedCallback( function () use ( $key, $lSince, $expiry ) {
                        $latency = 0.050; // latency skew (err towards keeping lock present)
-                       $age = ( microtime( true ) - $lSince + $latency );
+                       $age = ( $this->getCurrentTime() - $lSince + $latency );
                        if ( ( $age + $latency ) >= $expiry ) {
-                               $this->logger->warning( "Lock for $key held too long ($age sec)." );
+                               $this->logger->warning(
+                                       "Lock for {key} held too long ({age} sec).",
+                                       [ 'key' => $key, 'age' => $age ]
+                               );
                                return; // expired; it's not "safe" to delete the key
                        }
                        $this->unlock( $key );
@@ -550,6 +616,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         * @return bool Success
         */
        public function add( $key, $value, $exptime = 0 ) {
+               // @note: avoid lock() here since that method uses *this* method by default
                if ( $this->get( $key ) === false ) {
                        return $this->set( $key, $value, $exptime );
                }
@@ -563,7 +630,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         * @return int|bool New value or false on failure
         */
        public function incr( $key, $value = 1 ) {
-               if ( !$this->lock( $key ) ) {
+               if ( !$this->lock( $key, 1 ) ) {
                        return false;
                }
                $n = $this->get( $key );
@@ -601,14 +668,15 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         * @since 1.24
         */
        public function incrWithInit( $key, $ttl, $value = 1, $init = 1 ) {
+               $this->clearLastError();
                $newValue = $this->incr( $key, $value );
-               if ( $newValue === false ) {
+               if ( $newValue === false && !$this->getLastError() ) {
                        // No key set; initialize
                        $newValue = $this->add( $key, (int)$init, $ttl ) ? $init : false;
-               }
-               if ( $newValue === false ) {
-                       // Raced out initializing; increment
-                       $newValue = $this->incr( $key, $value );
+                       if ( $newValue === false && !$this->getLastError() ) {
+                               // Raced out initializing; increment
+                               $newValue = $this->incr( $key, $value );
+                       }
                }
 
                return $newValue;
@@ -700,7 +768,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         */
        protected function convertExpiry( $exptime ) {
                if ( $exptime != 0 && $exptime < ( 10 * self::TTL_YEAR ) ) {
-                       return time() + $exptime;
+                       return (int)$this->getCurrentTime() + $exptime;
                } else {
                        return $exptime;
                }
@@ -715,7 +783,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         */
        protected function convertToRelative( $exptime ) {
                if ( $exptime >= ( 10 * self::TTL_YEAR ) ) {
-                       $exptime -= time();
+                       $exptime -= (int)$this->getCurrentTime();
                        if ( $exptime <= 0 ) {
                                $exptime = 1;
                        }
@@ -757,7 +825,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         *
         * @since 1.27
         * @param string $class Key class
-        * @param string $component [optional] Key component (starting with a key collection name)
+        * @param string|null $component [optional] Key component (starting with a key collection name)
         * @return string Colon-delimited list of $keyspace followed by escaped components of $args
         */
        public function makeGlobalKey( $class, $component = null ) {
@@ -769,7 +837,7 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
         *
         * @since 1.27
         * @param string $class Key class
-        * @param string $component [optional] Key component (starting with a key collection name)
+        * @param string|null $component [optional] Key component (starting with a key collection name)
         * @return string Colon-delimited list of $keyspace followed by escaped components of $args
         */
        public function makeKey( $class, $component = null ) {
@@ -805,4 +873,20 @@ abstract class BagOStuff implements IExpiringStore, LoggerAwareInterface {
 
                return $map;
        }
+
+       /**
+        * @return float UNIX timestamp
+        * @codeCoverageIgnore
+        */
+       protected function getCurrentTime() {
+               return $this->wallClockOverride ?: microtime( true );
+       }
+
+       /**
+        * @param float|null &$time Mock UNIX timestamp for testing
+        * @codeCoverageIgnore
+        */
+       public function setMockTime( &$time ) {
+               $this->wallClockOverride =& $time;
+       }
 }