Merge "Don't fallback from uk to ru"
[lhc/web/wiklou.git] / includes / api / ApiStashEdit.php
index dd911d0..92cbe90 100644 (file)
@@ -20,6 +20,8 @@
  */
 
 use MediaWiki\Logger\LoggerFactory;
+use MediaWiki\MediaWikiServices;
+use Wikimedia\ScopedCallback;
 
 /**
  * Prepare an edit in shared cache so that it can be reused on edit
@@ -39,6 +41,7 @@ class ApiStashEdit extends ApiBase {
        const ERROR_PARSE = 'error_parse';
        const ERROR_CACHE = 'error_cache';
        const ERROR_UNCACHEABLE = 'uncacheable';
+       const ERROR_BUSY = 'busy';
 
        const PRESUME_FRESH_TTL_SEC = 30;
        const MAX_CACHE_TTL = 300; // 5 minutes
@@ -51,6 +54,7 @@ class ApiStashEdit extends ApiBase {
                        $this->dieUsage( 'This interface is not supported for bots', 'botsnotsupported' );
                }
 
+               $cache = ObjectCache::getLocalClusterInstance();
                $page = $this->getTitleOrPageId( $params );
                $title = $page->getTitle();
 
@@ -60,8 +64,25 @@ class ApiStashEdit extends ApiBase {
                        $this->dieUsage( 'Unsupported content model/format', 'badmodelformat' );
                }
 
-               // Trim and fix newlines so the key SHA1's match (see RequestContext::getText())
-               $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
+               $text = null;
+               $textHash = null;
+               if ( strlen( $params['stashedtexthash'] ) ) {
+                       // Load from cache since the client indicates the text is the same as last stash
+                       $textHash = $params['stashedtexthash'];
+                       $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
+                       $text = $cache->get( $textKey );
+                       if ( !is_string( $text ) ) {
+                               $this->dieUsage( 'No stashed text found with the given hash', 'missingtext' );
+                       }
+               } elseif ( $params['text'] !== null ) {
+                       // Trim and fix newlines so the key SHA1's match (see WebRequest::getText())
+                       $text = rtrim( str_replace( "\r\n", "\n", $params['text'] ) );
+                       $textHash = sha1( $text );
+               } else {
+                       $this->dieUsage(
+                               'The text or stashedtexthash parameter must be given', 'missingtextparam' );
+               }
+
                $textContent = ContentHandler::makeContent(
                        $text, $title, $params['contentmodel'], $params['contentformat'] );
 
@@ -113,46 +134,74 @@ class ApiStashEdit extends ApiBase {
                // The user will abort the AJAX request by pressing "save", so ignore that
                ignore_user_abort( true );
 
-               // Use the master DB for fast blocking locks
-               $dbw = wfGetDB( DB_MASTER );
-
-               // Get a key based on the source text, format, and user preferences
-               $key = self::getStashKey( $title, $content, $user );
-               // De-duplicate requests on the same key
                if ( $user->pingLimiter( 'stashedit' ) ) {
                        $status = 'ratelimited';
-               } elseif ( $dbw->lock( $key, __METHOD__, 1 ) ) {
-                       $status = self::parseAndStash( $page, $content, $user );
-                       $dbw->unlock( $key, __METHOD__ );
                } else {
-                       $status = 'busy';
+                       $status = self::parseAndStash( $page, $content, $user, $params['summary'] );
+                       $textKey = $cache->makeKey( 'stashedit', 'text', $textHash );
+                       $cache->set( $textKey, $text, self::MAX_CACHE_TTL );
                }
 
-               $this->getStats()->increment( "editstash.cache_stores.$status" );
+               $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
+               $stats->increment( "editstash.cache_stores.$status" );
 
-               $this->getResult()->addValue( null, $this->getModuleName(), [ 'status' => $status ] );
+               $this->getResult()->addValue(
+                       null,
+                       $this->getModuleName(),
+                       [
+                               'status' => $status,
+                               'texthash' => $textHash
+                       ]
+               );
        }
 
        /**
         * @param WikiPage $page
-        * @param Content $content
+        * @param Content $content Edit content
         * @param User $user
+        * @param string $summary Edit summary
         * @return integer ApiStashEdit::ERROR_* constant
         * @since 1.25
         */
-       public static function parseAndStash( WikiPage $page, Content $content, User $user ) {
+       public static function parseAndStash( WikiPage $page, Content $content, User $user, $summary ) {
                $cache = ObjectCache::getLocalClusterInstance();
                $logger = LoggerFactory::getInstance( 'StashEdit' );
 
-               $format = $content->getDefaultFormat();
-               $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
                $title = $page->getTitle();
+               $key = self::getStashKey( $title, self::getContentHash( $content ), $user );
 
-               if ( $editInfo && $editInfo->output ) {
-                       $key = self::getStashKey( $title, $content, $user );
+               // Use the master DB for fast blocking locks
+               $dbw = wfGetDB( DB_MASTER );
+               if ( !$dbw->lock( $key, __METHOD__, 1 ) ) {
+                       // De-duplicate requests on the same key
+                       return self::ERROR_BUSY;
+               }
+               /** @noinspection PhpUnusedLocalVariableInspection */
+               $unlocker = new ScopedCallback( function () use ( $dbw, $key ) {
+                       $dbw->unlock( $key, __METHOD__ );
+               } );
+
+               $cutoffTime = time() - self::PRESUME_FRESH_TTL_SEC;
 
+               // Reuse any freshly build matching edit stash cache
+               $editInfo = $cache->get( $key );
+               if ( $editInfo && wfTimestamp( TS_UNIX, $editInfo->timestamp ) >= $cutoffTime ) {
+                       $alreadyCached = true;
+               } else {
+                       $format = $content->getDefaultFormat();
+                       $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
+                       $alreadyCached = false;
+               }
+
+               if ( $editInfo && $editInfo->output ) {
                        // Let extensions add ParserOutput metadata or warm other caches
-                       Hooks::run( 'ParserOutputStashForEdit', [ $page, $content, $editInfo->output ] );
+                       Hooks::run( 'ParserOutputStashForEdit',
+                               [ $page, $content, $editInfo->output, $summary, $user ] );
+
+                       if ( $alreadyCached ) {
+                               $logger->debug( "Already cached parser output for key '$key' ('$title')." );
+                               return self::ERROR_NONE;
+                       }
 
                        list( $stashInfo, $ttl, $code ) = self::buildStashValue(
                                $editInfo->pstContent,
@@ -179,77 +228,6 @@ class ApiStashEdit extends ApiBase {
                return self::ERROR_PARSE;
        }
 
-       /**
-        * Attempt to cache PST content and corresponding parser output in passing
-        *
-        * This method can be called when the output was already generated for other
-        * reasons. Parsing should not be done just to call this method, however.
-        * $pstOpts must be that of the user doing the edit preview. If $pOpts does
-        * not match the options of WikiPage::makeParserOptions( 'canonical' ), this
-        * will do nothing. Provided the values are cacheable, they will be stored
-        * in memcached so that final edit submission might make use of them.
-        *
-        * @param Page|Article|WikiPage $page Page title
-        * @param Content $content Proposed page content
-        * @param Content $pstContent The result of preSaveTransform() on $content
-        * @param ParserOutput $pOut The result of getParserOutput() on $pstContent
-        * @param ParserOptions $pstOpts Options for $pstContent (MUST be for prospective author)
-        * @param ParserOptions $pOpts Options for $pOut
-        * @param string $timestamp TS_MW timestamp of parser output generation
-        * @return bool Success
-        */
-       public static function stashEditFromPreview(
-               Page $page, Content $content, Content $pstContent, ParserOutput $pOut,
-               ParserOptions $pstOpts, ParserOptions $pOpts, $timestamp
-       ) {
-               $cache = ObjectCache::getLocalClusterInstance();
-               $logger = LoggerFactory::getInstance( 'StashEdit' );
-
-               // getIsPreview() controls parser function behavior that references things
-               // like user/revision that don't exists yet. The user/text should already
-               // be set correctly by callers, just double check the preview flag.
-               if ( !$pOpts->getIsPreview() ) {
-                       return false; // sanity
-               } elseif ( $pOpts->getIsSectionPreview() ) {
-                       return false; // short-circuit (need the full content)
-               }
-
-               // PST parser options are for the user (handles signatures, etc...)
-               $user = $pstOpts->getUser();
-               // Get a key based on the source text, format, and user preferences
-               $title = $page->getTitle();
-               $key = self::getStashKey( $title, $content, $user );
-
-               // Parser output options must match cannonical options.
-               // Treat some options as matching that are different but don't matter.
-               $canonicalPOpts = $page->makeParserOptions( 'canonical' );
-               $canonicalPOpts->setIsPreview( true ); // force match
-               $canonicalPOpts->setTimestamp( $pOpts->getTimestamp() ); // force match
-               if ( !$pOpts->matches( $canonicalPOpts ) ) {
-                       $logger->info( "Uncacheable preview output for key '$key' ('$title') [options]." );
-                       return false;
-               }
-
-               // Set the time the output was generated
-               $pOut->setCacheTime( wfTimestampNow() );
-
-               // Build a value to cache with a proper TTL
-               list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp, $user );
-               if ( !$stashInfo ) {
-                       $logger->info( "Uncacheable parser output for key '$key' ('$title') [rev/TTL]." );
-                       return false;
-               }
-
-               $ok = $cache->set( $key, $stashInfo, $ttl );
-               if ( !$ok ) {
-                       $logger->error( "Failed to cache preview parser output for key '$key' ('$title')." );
-               } else {
-                       $logger->debug( "Cached preview output for key '$key'." );
-               }
-
-               return $ok;
-       }
-
        /**
         * Check that a prepared edit is in cache and still up-to-date
         *
@@ -274,9 +252,9 @@ class ApiStashEdit extends ApiBase {
 
                $cache = ObjectCache::getLocalClusterInstance();
                $logger = LoggerFactory::getInstance( 'StashEdit' );
-               $stats = RequestContext::getMain()->getStats();
+               $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
 
-               $key = self::getStashKey( $title, $content, $user );
+               $key = self::getStashKey( $title, self::getContentHash( $content ), $user );
                $editInfo = $cache->get( $key );
                if ( !is_object( $editInfo ) ) {
                        $start = microtime( true );
@@ -284,7 +262,7 @@ class ApiStashEdit extends ApiBase {
                        // so as to use its results and make use of the time spent parsing.
                        // Skip this logic if there no master connection in case this method
                        // is called on an HTTP GET request for some reason.
-                       $lb = wfGetLB();
+                       $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
                        $dbw = $lb->getAnyOpenConnection( $lb->getWriterIndex() );
                        if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
                                $editInfo = $cache->get( $key );
@@ -303,27 +281,37 @@ class ApiStashEdit extends ApiBase {
 
                $age = time() - wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
                if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
+                       // Assume nothing changed in this time
                        $stats->increment( 'editstash.cache_hits.presumed_fresh' );
                        $logger->debug( "Timestamp-based cache hit for key '$key' (age: $age sec)." );
-                       return $editInfo; // assume nothing changed
                } elseif ( isset( $editInfo->edits ) && $editInfo->edits === $user->getEditCount() ) {
                        // Logged-in user made no local upload/template edits in the meantime
                        $stats->increment( 'editstash.cache_hits.presumed_fresh' );
                        $logger->debug( "Edit count based cache hit for key '$key' (age: $age sec)." );
-                       return $editInfo;
                } elseif ( $user->isAnon()
                        && self::lastEditTime( $user ) < $editInfo->output->getCacheTime()
                ) {
                        // Logged-out user made no local upload/template edits in the meantime
                        $stats->increment( 'editstash.cache_hits.presumed_fresh' );
                        $logger->debug( "Edit check based cache hit for key '$key' (age: $age sec)." );
-                       return $editInfo;
+               } else {
+                       // User may have changed included content
+                       $editInfo = false;
                }
 
-               $stats->increment( 'editstash.cache_misses.proven_stale' );
-               $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
+               if ( !$editInfo ) {
+                       $stats->increment( 'editstash.cache_misses.proven_stale' );
+                       $logger->info( "Stale cache for key '$key'; old key with outside edits. (age: $age sec)" );
+               } elseif ( $editInfo->output->getFlag( 'vary-revision' ) ) {
+                       // This can be used for the initial parse, e.g. for filters or doEditContent(),
+                       // but a second parse will be triggered in doEditUpdates(). This is not optimal.
+                       $logger->info( "Cache for key '$key' ('$title') has vary_revision." );
+               } elseif ( $editInfo->output->getFlag( 'vary-revision-id' ) ) {
+                       // Similar to the above if we didn't guess the ID correctly.
+                       $logger->info( "Cache for key '$key' ('$title') has vary_revision_id." );
+               }
 
-               return false;
+               return $editInfo;
        }
 
        /**
@@ -331,7 +319,7 @@ class ApiStashEdit extends ApiBase {
         * @return string|null TS_MW timestamp or null
         */
        private static function lastEditTime( User $user ) {
-               $time = wfGetDB( DB_SLAVE )->selectField(
+               $time = wfGetDB( DB_REPLICA )->selectField(
                        'recentchanges',
                        'MAX(rc_timestamp)',
                        [ 'rc_user_text' => $user->getName() ],
@@ -341,6 +329,20 @@ class ApiStashEdit extends ApiBase {
                return wfTimestampOrNull( TS_MW, $time );
        }
 
+       /**
+        * Get hash of the content, factoring in model/format
+        *
+        * @param Content $content
+        * @return string
+        */
+       private static function getContentHash( Content $content ) {
+               return sha1( implode( "\n", [
+                       $content->getModel(),
+                       $content->getDefaultFormat(),
+                       $content->serialize( $content->getDefaultFormat() )
+               ] ) );
+       }
+
        /**
         * Get the temporary prepared edit stash key for a user
         *
@@ -349,22 +351,19 @@ class ApiStashEdit extends ApiBase {
         *   - b) The parser output was made from the PST using cannonical matching options
         *
         * @param Title $title
-        * @param Content $content
+        * @param string $contentHash Result of getContentHash()
         * @param User $user User to get parser options from
         * @return string
         */
-       private static function getStashKey( Title $title, Content $content, User $user ) {
-               $hash = sha1( implode( ':', [
+       private static function getStashKey( Title $title, $contentHash, User $user ) {
+               return ObjectCache::getLocalClusterInstance()->makeKey(
+                       'prepared-edit',
+                       md5( $title->getPrefixedDBkey() ),
                        // Account for the edit model/text
-                       $content->getModel(),
-                       $content->getDefaultFormat(),
-                       sha1( $content->serialize( $content->getDefaultFormat() ) ),
+                       $contentHash,
                        // Account for user name related variables like signatures
-                       $user->getId(),
-                       md5( $user->getName() )
-               ] ) );
-
-               return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
+                       md5( $user->getId() . "\n" . $user->getName() )
+               );
        }
 
        /**
@@ -372,7 +371,7 @@ class ApiStashEdit extends ApiBase {
         *
         * This makes a simple version of WikiPage::prepareContentForEdit() as stash info
         *
-        * @param Content $pstContent
+        * @param Content $pstContent Pre-Save transformed content
         * @param ParserOutput $parserOutput
         * @param string $timestamp TS_MW
         * @param User $user
@@ -387,8 +386,6 @@ class ApiStashEdit extends ApiBase {
                $ttl = min( $parserOutput->getCacheExpiry() - $since, self::MAX_CACHE_TTL );
                if ( $ttl <= 0 ) {
                        return [ null, 0, 'no_ttl' ];
-               } elseif ( $parserOutput->getFlag( 'vary-revision' ) ) {
-                       return [ null, 0, 'vary_revision' ];
                }
 
                // Only store what is actually needed
@@ -416,7 +413,14 @@ class ApiStashEdit extends ApiBase {
                        ],
                        'text' => [
                                ApiBase::PARAM_TYPE => 'text',
-                               ApiBase::PARAM_REQUIRED => true
+                               ApiBase::PARAM_DFLT => null
+                       ],
+                       'stashedtexthash' => [
+                               ApiBase::PARAM_TYPE => 'string',
+                               ApiBase::PARAM_DFLT => null
+                       ],
+                       'summary' => [
+                               ApiBase::PARAM_TYPE => 'string',
                        ],
                        'contentmodel' => [
                                ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),