Make edit stash keys less preference sensitive
[lhc/web/wiklou.git] / includes / api / ApiStashEdit.php
index 5efefbd..01153a5 100644 (file)
@@ -46,6 +46,10 @@ class ApiStashEdit extends ApiBase {
                $user = $this->getUser();
                $params = $this->extractRequestParams();
 
+               if ( $user->isBot() ) { // sanity
+                       $this->dieUsage( 'This interface is not supported for bots', 'botsnotsupported' );
+               }
+
                $page = $this->getTitleOrPageId( $params );
                $title = $page->getTitle();
 
@@ -123,6 +127,8 @@ class ApiStashEdit extends ApiBase {
                        $status = 'busy';
                }
 
+               $this->getStats()->increment( "editstash.cache_stores.$status" );
+
                $this->getResult()->addValue( null, $this->getModuleName(), [ 'status' => $status ] );
        }
 
@@ -147,13 +153,15 @@ class ApiStashEdit extends ApiBase {
                        Hooks::run( 'ParserOutputStashForEdit', [ $page, $content, $editInfo->output ] );
 
                        list( $stashInfo, $ttl ) = self::buildStashValue(
-                               $editInfo->pstContent, $editInfo->output, $editInfo->timestamp
+                               $editInfo->pstContent,
+                               $editInfo->output,
+                               $editInfo->timestamp,
+                               $user
                        );
 
                        if ( $stashInfo ) {
                                $ok = $cache->set( $key, $stashInfo, $ttl );
                                if ( $ok ) {
-
                                        $logger->debug( "Cached parser output for key '$key'." );
                                        return self::ERROR_NONE;
                                } else {
@@ -223,7 +231,7 @@ class ApiStashEdit extends ApiBase {
                $pOut->setCacheTime( wfTimestampNow() );
 
                // Build a value to cache with a proper TTL
-               list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp );
+               list( $stashInfo, $ttl ) = self::buildStashValue( $pstContent, $pOut, $timestamp, $user );
                if ( !$stashInfo ) {
                        $logger->info( "Uncacheable parser output for key '$key' (rev/TTL)." );
                        return false;
@@ -257,6 +265,10 @@ class ApiStashEdit extends ApiBase {
         * @return stdClass|bool Returns false on cache miss
         */
        public static function checkCache( Title $title, Content $content, User $user ) {
+               if ( $user->isBot() ) {
+                       return false; // bots never stash - don't pollute stats
+               }
+
                $cache = ObjectCache::getLocalClusterInstance();
                $logger = LoggerFactory::getInstance( 'StashEdit' );
                $stats = RequestContext::getMain()->getStats();
@@ -291,6 +303,18 @@ class ApiStashEdit extends ApiBase {
                        $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;
                }
 
                $dbr = wfGetDB( DB_SLAVE );
@@ -353,6 +377,21 @@ class ApiStashEdit extends ApiBase {
                return $editInfo;
        }
 
+       /**
+        * @param User $user
+        * @return string|null TS_MW timestamp or null
+        */
+       private static function lastEditTime( User $user ) {
+               $time = wfGetDB( DB_SLAVE )->selectField(
+                       'recentchanges',
+                       'MAX(rc_timestamp)',
+                       [ 'rc_user_text' => $user->getName() ],
+                       __METHOD__
+               );
+
+               return wfTimestampOrNull( TS_MW, $time );
+       }
+
        /**
         * Get the temporary prepared edit stash key for a user
         *
@@ -365,13 +404,17 @@ class ApiStashEdit extends ApiBase {
         * @param User $user User to get parser options from
         * @return string
         */
-       protected static function getStashKey( Title $title, Content $content, User $user ) {
+       private static function getStashKey( Title $title, Content $content, User $user ) {
                $hash = sha1( implode( ':', [
+                       // Account for the edit model/text
                        $content->getModel(),
                        $content->getDefaultFormat(),
                        sha1( $content->serialize( $content->getDefaultFormat() ) ),
-                       $user->getId() ?: md5( $user->getName() ), // account for user parser options
-                       $user->getId() ? $user->getDBTouched() : '-' // handle preference change races
+                       // Account for user name related variables like signatures
+                       $user->getId(),
+                       md5( $user->getName() ),
+                       (string)$user->getOption( 'nickname' ),
+                       (int)$user->getBoolOption( 'fancysig' )
                ] ) );
 
                return wfMemcKey( 'prepared-edit', md5( $title->getPrefixedDBkey() ), $hash );
@@ -385,12 +428,14 @@ class ApiStashEdit extends ApiBase {
         * @param Content $pstContent
         * @param ParserOutput $parserOutput
         * @param string $timestamp TS_MW
+        * @param User $user
         * @return array (stash info array, TTL in seconds) or (null, 0)
         */
-       protected static function buildStashValue(
-               Content $pstContent, ParserOutput $parserOutput, $timestamp
+       private static function buildStashValue(
+               Content $pstContent, ParserOutput $parserOutput, $timestamp, User $user
        ) {
-               // If an item is renewed, mind the cache TTL determined by config and parser functions
+               // If an item is renewed, mind the cache TTL determined by config and parser functions.
+               // Put an upper limit on the TTL for sanity to avoid extreme template/file staleness.
                $since = time() - wfTimestamp( TS_UNIX, $parserOutput->getTimestamp() );
                $ttl = min( $parserOutput->getCacheExpiry() - $since, 5 * 60 );
 
@@ -399,7 +444,8 @@ class ApiStashEdit extends ApiBase {
                        $stashInfo = (object)[
                                'pstContent' => $pstContent,
                                'output'     => $parserOutput,
-                               'timestamp'  => $timestamp
+                               'timestamp'  => $timestamp,
+                               'edits'      => $user->getEditCount()
                        ];
                        return [ $stashInfo, $ttl ];
                }