MediaWiki  master
PageEditStash.php
Go to the documentation of this file.
1 <?php
23 namespace MediaWiki\Storage;
24 
25 use BagOStuff;
26 use Content;
27 use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
36 use ParserOutput;
37 use Psr\Log\LoggerInterface;
38 use stdClass;
40 use Wikimedia\ScopedCallback;
41 use WikiPage;
42 
50  private $cache;
52  private $lb;
54  private $logger;
56  private $stats;
58  private $hookRunner;
62  private $userFactory;
64  private $initiator;
65 
66  public const ERROR_NONE = 'stashed';
67  public const ERROR_PARSE = 'error_parse';
68  public const ERROR_CACHE = 'error_cache';
69  public const ERROR_UNCACHEABLE = 'uncacheable';
70  public const ERROR_BUSY = 'busy';
71 
72  public const PRESUME_FRESH_TTL_SEC = 30;
73  public const MAX_CACHE_TTL = 300; // 5 minutes
74  public const MAX_SIGNATURE_TTL = 60;
75 
76  private const MAX_CACHE_RECENT = 2;
77 
78  public const INITIATOR_USER = 1;
79  public const INITIATOR_JOB_OR_CLI = 2;
80 
91  public function __construct(
94  LoggerInterface $logger,
95  StatsdDataFactoryInterface $stats,
98  HookContainer $hookContainer,
100  ) {
101  $this->cache = $cache;
102  $this->lb = $lb;
103  $this->logger = $logger;
104  $this->stats = $stats;
105  $this->userEditTracker = $userEditTracker;
106  $this->userFactory = $userFactory;
107  $this->hookRunner = new HookRunner( $hookContainer );
108  $this->initiator = $initiator;
109  }
110 
118  public function parseAndCache( WikiPage $page, Content $content, UserIdentity $user, string $summary ) {
120 
121  $key = $this->getStashKey( $page, $this->getContentHash( $content ), $user );
122  $fname = __METHOD__;
123 
124  // Use the primary DB to allow for fast blocking locks on the "save path" where this
125  // value might actually be used to complete a page edit. If the edit submission request
126  // happens before this edit stash requests finishes, then the submission will block until
127  // the stash request finishes parsing. For the lock acquisition below, there is not much
128  // need to duplicate parsing of the same content/user/summary bundle, so try to avoid
129  // blocking at all here.
130  $dbw = $this->lb->getConnectionRef( DB_PRIMARY );
131  if ( !$dbw->lock( $key, $fname, 0 ) ) {
132  // De-duplicate requests on the same key
133  return self::ERROR_BUSY;
134  }
136  $unlocker = new ScopedCallback( static function () use ( $dbw, $key, $fname ) {
137  $dbw->unlock( $key, $fname );
138  } );
139 
140  $cutoffTime = time() - self::PRESUME_FRESH_TTL_SEC;
141 
142  // Reuse any freshly build matching edit stash cache
143  $editInfo = $this->getStashValue( $key );
144  if ( $editInfo && wfTimestamp( TS_UNIX, $editInfo->timestamp ) >= $cutoffTime ) {
145  $alreadyCached = true;
146  } else {
147  $format = $content->getDefaultFormat();
148  $editInfo = $page->prepareContentForEdit( $content, null, $user, $format, false );
149  $editInfo->output->setCacheTime( $editInfo->timestamp );
150  $alreadyCached = false;
151  }
152 
153  $logContext = [ 'cachekey' => $key, 'title' => (string)$page ];
154 
155  if ( $editInfo && $editInfo->output ) {
156  // Let extensions add ParserOutput metadata or warm other caches
157  $legacyUser = $this->userFactory->newFromUserIdentity( $user );
158  $this->hookRunner->onParserOutputStashForEdit(
159  $page, $content, $editInfo->output, $summary, $legacyUser );
160 
161  if ( $alreadyCached ) {
162  $logger->debug( "Parser output for key '{cachekey}' already cached.", $logContext );
163 
164  return self::ERROR_NONE;
165  }
166 
167  $code = $this->storeStashValue(
168  $key,
169  $editInfo->pstContent,
170  $editInfo->output,
171  $editInfo->timestamp,
172  $user
173  );
174 
175  if ( $code === true ) {
176  $logger->debug( "Cached parser output for key '{cachekey}'.", $logContext );
177 
178  return self::ERROR_NONE;
179  } elseif ( $code === 'uncacheable' ) {
180  $logger->info(
181  "Uncacheable parser output for key '{cachekey}' [{code}].",
182  $logContext + [ 'code' => $code ]
183  );
184 
186  } else {
187  $logger->error(
188  "Failed to cache parser output for key '{cachekey}'.",
189  $logContext + [ 'code' => $code ]
190  );
191 
192  return self::ERROR_CACHE;
193  }
194  }
195 
196  return self::ERROR_PARSE;
197  }
198 
219  public function checkCache( PageIdentity $page, Content $content, UserIdentity $user ) {
220  $legacyUser = $this->userFactory->newFromUserIdentity( $user );
221  if (
222  // The context is not an HTTP POST request
223  !$legacyUser->getRequest()->wasPosted() ||
224  // The context is a CLI script or a job runner HTTP POST request
225  $this->initiator !== self::INITIATOR_USER ||
226  // The editor account is a known bot
227  $legacyUser->isBot()
228  ) {
229  // Avoid wasted queries and statsd pollution
230  return false;
231  }
232 
234 
235  $key = $this->getStashKey( $page, $this->getContentHash( $content ), $user );
236  $logContext = [
237  'key' => $key,
238  'title' => (string)$page,
239  'user' => $user->getName()
240  ];
241 
242  $editInfo = $this->getAndWaitForStashValue( $key );
243  if ( !is_object( $editInfo ) || !$editInfo->output ) {
244  $this->incrStatsByContent( 'cache_misses.no_stash', $content );
245  if ( $this->recentStashEntryCount( $user ) > 0 ) {
246  $logger->info( "Empty cache for key '{key}' but not for user.", $logContext );
247  } else {
248  $logger->debug( "Empty cache for key '{key}'.", $logContext );
249  }
250 
251  return false;
252  }
253 
254  $age = time() - (int)wfTimestamp( TS_UNIX, $editInfo->output->getCacheTime() );
255  $logContext['age'] = $age;
256 
257  $isCacheUsable = true;
258  if ( $age <= self::PRESUME_FRESH_TTL_SEC ) {
259  // Assume nothing changed in this time
260  $this->incrStatsByContent( 'cache_hits.presumed_fresh', $content );
261  $logger->debug( "Timestamp-based cache hit for key '{key}'.", $logContext );
262  } elseif ( !$user->isRegistered() ) {
263  $lastEdit = $this->lastEditTime( $user );
264  $cacheTime = $editInfo->output->getCacheTime();
265  if ( $lastEdit < $cacheTime ) {
266  // Logged-out user made no local upload/template edits in the meantime
267  $this->incrStatsByContent( 'cache_hits.presumed_fresh', $content );
268  $logger->debug( "Edit check based cache hit for key '{key}'.", $logContext );
269  } else {
270  $isCacheUsable = false;
271  $this->incrStatsByContent( 'cache_misses.proven_stale', $content );
272  $logger->info( "Stale cache for key '{key}' due to outside edits.", $logContext );
273  }
274  } else {
275  if ( $editInfo->edits === $this->userEditTracker->getUserEditCount( $user ) ) {
276  // Logged-in user made no local upload/template edits in the meantime
277  $this->incrStatsByContent( 'cache_hits.presumed_fresh', $content );
278  $logger->debug( "Edit count based cache hit for key '{key}'.", $logContext );
279  } else {
280  $isCacheUsable = false;
281  $this->incrStatsByContent( 'cache_misses.proven_stale', $content );
282  $logger->info( "Stale cache for key '{key}'due to outside edits.", $logContext );
283  }
284  }
285 
286  if ( !$isCacheUsable ) {
287  return false;
288  }
289 
290  if ( $editInfo->output->getOutputFlag( ParserOutputFlags::VARY_REVISION ) ) {
291  // This can be used for the initial parse, e.g. for filters or doUserEditContent(),
292  // but a second parse will be triggered in doEditUpdates() no matter what
293  $logger->info(
294  "Cache for key '{key}' has vary-revision; post-insertion parse inevitable.",
295  $logContext
296  );
297  } else {
298  static $flagsMaybeReparse = [
299  // Similar to the above if we didn't guess the ID correctly
300  ParserOutputFlags::VARY_REVISION_ID,
301  // Similar to the above if we didn't guess the timestamp correctly
302  ParserOutputFlags::VARY_REVISION_TIMESTAMP,
303  // Similar to the above if we didn't guess the content correctly
304  ParserOutputFlags::VARY_REVISION_SHA1,
305  // Similar to the above if we didn't guess page ID correctly
306  ParserOutputFlags::VARY_PAGE_ID,
307  ];
308  foreach ( $flagsMaybeReparse as $flag ) {
309  if ( $editInfo->output->getOutputFlag( $flag ) ) {
310  $logger->debug(
311  "Cache for key '{key}' has $flag; post-insertion parse possible.",
312  $logContext
313  );
314  }
315  }
316  }
317 
318  return $editInfo;
319  }
320 
325  private function incrStatsByContent( $subkey, Content $content ) {
326  $this->stats->increment( 'editstash.' . $subkey ); // overall for b/c
327  $this->stats->increment( 'editstash_by_model.' . $content->getModel() . '.' . $subkey );
328  }
329 
334  private function getAndWaitForStashValue( $key ) {
335  $editInfo = $this->getStashValue( $key );
336 
337  if ( !$editInfo ) {
338  $start = microtime( true );
339  // We ignore user aborts and keep parsing. Block on any prior parsing
340  // so as to use its results and make use of the time spent parsing.
341  // Skip this logic if there no primary connection in case this method
342  // is called on an HTTP GET request for some reason.
343  $dbw = $this->lb->getAnyOpenConnection( $this->lb->getWriterIndex() );
344  if ( $dbw && $dbw->lock( $key, __METHOD__, 30 ) ) {
345  $editInfo = $this->getStashValue( $key );
346  $dbw->unlock( $key, __METHOD__ );
347  }
348 
349  $timeMs = 1000 * max( 0, microtime( true ) - $start );
350  $this->stats->timing( 'editstash.lock_wait_time', $timeMs );
351  }
352 
353  return $editInfo;
354  }
355 
360  public function fetchInputText( $textHash ) {
361  $textKey = $this->cache->makeKey( 'stashedit', 'text', $textHash );
362 
363  return $this->cache->get( $textKey );
364  }
365 
371  public function stashInputText( $text, $textHash ) {
372  $textKey = $this->cache->makeKey( 'stashedit', 'text', $textHash );
373 
374  return $this->cache->set(
375  $textKey,
376  $text,
377  self::MAX_CACHE_TTL,
379  );
380  }
381 
386  private function lastEditTime( UserIdentity $user ) {
387  $db = $this->lb->getConnectionRef( DB_REPLICA );
388 
389  $time = $db->newSelectQueryBuilder()
390  ->select( 'MAX(rc_timestamp)' )
391  ->from( 'recentchanges' )
392  ->join( 'actor', null, 'actor_id=rc_actor' )
393  ->where( [ 'actor_name' => $user->getName() ] )
394  ->caller( __METHOD__ )
395  ->fetchField();
396 
397  return wfTimestampOrNull( TS_MW, $time );
398  }
399 
406  private function getContentHash( Content $content ) {
407  return sha1( implode( "\n", [
408  $content->getModel(),
409  $content->getDefaultFormat(),
410  $content->serialize( $content->getDefaultFormat() )
411  ] ) );
412  }
413 
426  private function getStashKey( PageIdentity $page, $contentHash, UserIdentity $user ) {
427  return $this->cache->makeKey(
428  'stashedit-info-v1',
429  md5( "{$page->getNamespace()}\n{$page->getDBkey()}" ),
430  // Account for the edit model/text
431  $contentHash,
432  // Account for user name related variables like signatures
433  md5( "{$user->getId()}\n{$user->getName()}" )
434  );
435  }
436 
441  private function getStashValue( $key ) {
442  $stashInfo = $this->cache->get( $key );
443  if ( is_object( $stashInfo ) && $stashInfo->output instanceof ParserOutput ) {
444  return $stashInfo;
445  }
446 
447  return false;
448  }
449 
462  private function storeStashValue(
463  $key,
464  Content $pstContent,
465  ParserOutput $parserOutput,
466  $timestamp,
467  UserIdentity $user
468  ) {
469  // If an item is renewed, mind the cache TTL determined by config and parser functions.
470  // Put an upper limit on the TTL to avoid extreme template/file staleness.
471  $age = time() - (int)wfTimestamp( TS_UNIX, $parserOutput->getCacheTime() );
472  $ttl = min( $parserOutput->getCacheExpiry() - $age, self::MAX_CACHE_TTL );
473  // Avoid extremely stale user signature timestamps (T84843)
474  if ( $parserOutput->getOutputFlag( ParserOutputFlags::USER_SIGNATURE ) ) {
475  $ttl = min( $ttl, self::MAX_SIGNATURE_TTL );
476  }
477 
478  if ( $ttl <= 0 ) {
479  return 'uncacheable'; // low TTL due to a tag, magic word, or signature?
480  }
481 
482  // Store what is actually needed and split the output into another key (T204742)
483  $stashInfo = (object)[
484  'pstContent' => $pstContent,
485  'output' => $parserOutput,
486  'timestamp' => $timestamp,
487  'edits' => $user->isRegistered() ? $this->userEditTracker->getUserEditCount( $user ) : null,
488  ];
489 
490  $ok = $this->cache->set( $key, $stashInfo, $ttl, BagOStuff::WRITE_ALLOW_SEGMENTS );
491  if ( $ok ) {
492  // These blobs can waste slots in low cardinality memcached slabs
493  $this->pruneExcessStashedEntries( $user, $key );
494  }
495 
496  return $ok ? true : 'store_error';
497  }
498 
503  private function pruneExcessStashedEntries( UserIdentity $user, $newKey ) {
504  $key = $this->cache->makeKey( 'stash-edit-recent', sha1( $user->getName() ) );
505 
506  $keyList = $this->cache->get( $key ) ?: [];
507  if ( count( $keyList ) >= self::MAX_CACHE_RECENT ) {
508  $oldestKey = array_shift( $keyList );
509  $this->cache->delete( $oldestKey, BagOStuff::WRITE_PRUNE_SEGMENTS );
510  }
511 
512  $keyList[] = $newKey;
513  $this->cache->set( $key, $keyList, 2 * self::MAX_CACHE_TTL );
514  }
515 
520  private function recentStashEntryCount( UserIdentity $user ) {
521  $key = $this->cache->makeKey( 'stash-edit-recent', sha1( $user->getName() ) );
522 
523  return count( $this->cache->get( $key ) ?: [] );
524  }
525 }
MediaWiki\Storage\PageEditStash\stashInputText
stashInputText( $text, $textHash)
Definition: PageEditStash.php:371
Page\PageIdentity
Interface for objects (potentially) representing an editable wiki page.
Definition: PageIdentity.php:64
MediaWiki\Storage\PageEditStash\fetchInputText
fetchInputText( $textHash)
Definition: PageEditStash.php:360
CacheTime\getCacheExpiry
getCacheExpiry()
Returns the number of seconds after which this object should expire.
Definition: CacheTime.php:142
ParserOutput
Definition: ParserOutput.php:35
MediaWiki\Storage\PageEditStash\ERROR_PARSE
const ERROR_PARSE
Definition: PageEditStash.php:67
MediaWiki\Storage\PageEditStash\__construct
__construct(BagOStuff $cache, ILoadBalancer $lb, LoggerInterface $logger, StatsdDataFactoryInterface $stats, UserEditTracker $userEditTracker, UserFactory $userFactory, HookContainer $hookContainer, $initiator)
Definition: PageEditStash.php:91
Parser\ParserOutputFlags
Definition: ParserOutputFlags.php:41
true
return true
Definition: router.php:90
MediaWiki\Storage\PageEditStash\getContentHash
getContentHash(Content $content)
Get hash of the content, factoring in model/format.
Definition: PageEditStash.php:406
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1665
BagOStuff\WRITE_ALLOW_SEGMENTS
const WRITE_ALLOW_SEGMENTS
Definition: BagOStuff.php:122
MediaWiki\Storage\PageEditStash\incrStatsByContent
incrStatsByContent( $subkey, Content $content)
Definition: PageEditStash.php:325
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:62
MediaWiki\Storage\PageEditStash\ERROR_CACHE
const ERROR_CACHE
Definition: PageEditStash.php:68
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:86
MediaWiki\Storage\PageEditStash\$userEditTracker
UserEditTracker $userEditTracker
Definition: PageEditStash.php:60
WikiPage\prepareContentForEdit
prepareContentForEdit(Content $content, RevisionRecord $revision=null, UserIdentity $user=null, $serialFormat=null, $useCache=true)
Prepare content which is about to be saved.
Definition: WikiPage.php:2032
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:39
MediaWiki\Storage\PageEditStash\$logger
LoggerInterface $logger
Definition: PageEditStash.php:54
ParserOutput\getOutputFlag
getOutputFlag(string $name)
Provides a uniform interface to various boolean flags stored in the ParserOutput.
Definition: ParserOutput.php:1424
MediaWiki\Storage\PageEditStash\$hookRunner
ParserOutputStashForEditHook $hookRunner
Definition: PageEditStash.php:58
MediaWiki\Storage\PageEditStash\PRESUME_FRESH_TTL_SEC
const PRESUME_FRESH_TTL_SEC
Definition: PageEditStash.php:72
MediaWiki\Storage\Hook\ParserOutputStashForEditHook
This is a hook handler interface, see docs/Hooks.md.
Definition: ParserOutputStashForEditHook.php:17
MediaWiki\Storage\PageEditStash
Class for managing stashed edits used by the page updater classes.
Definition: PageEditStash.php:48
MediaWiki\User\UserIdentity\isRegistered
isRegistered()
MediaWiki\Storage\PageEditStash\$userFactory
UserFactory $userFactory
Definition: PageEditStash.php:62
wfTimestampOrNull
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
Definition: GlobalFunctions.php:1681
MediaWiki\User\UserIdentity\getName
getName()
MediaWiki\Storage\PageEditStash\getStashKey
getStashKey(PageIdentity $page, $contentHash, UserIdentity $user)
Get the temporary prepared edit stash key for a user.
Definition: PageEditStash.php:426
MediaWiki\Storage\PageEditStash\lastEditTime
lastEditTime(UserIdentity $user)
Definition: PageEditStash.php:386
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
MediaWiki\Storage\PageEditStash\$initiator
int $initiator
Definition: PageEditStash.php:64
BagOStuff\WRITE_PRUNE_SEGMENTS
const WRITE_PRUNE_SEGMENTS
Definition: BagOStuff.php:123
MediaWiki\Storage\PageEditStash\getAndWaitForStashValue
getAndWaitForStashValue( $key)
Definition: PageEditStash.php:334
$content
$content
Definition: router.php:76
DB_PRIMARY
const DB_PRIMARY
Definition: defines.php:27
MediaWiki\Storage\PageEditStash\storeStashValue
storeStashValue( $key, Content $pstContent, ParserOutput $parserOutput, $timestamp, UserIdentity $user)
Build a value to store in memcached based on the PST content and parser output.
Definition: PageEditStash.php:462
MediaWiki\Storage\PageEditStash\$stats
StatsdDataFactoryInterface $stats
Definition: PageEditStash.php:56
MediaWiki\Storage\PageEditStash\checkCache
checkCache(PageIdentity $page, Content $content, UserIdentity $user)
Check that a prepared edit is in cache and still up-to-date.
Definition: PageEditStash.php:219
MediaWiki\Storage\PageEditStash\pruneExcessStashedEntries
pruneExcessStashedEntries(UserIdentity $user, $newKey)
Definition: PageEditStash.php:503
MediaWiki\Storage\PageEditStash\getStashValue
getStashValue( $key)
Definition: PageEditStash.php:441
MediaWiki\Storage
Definition: BlobAccessException.php:23
Content
Base interface for content objects.
Definition: Content.php:35
MediaWiki\Storage\PageEditStash\INITIATOR_USER
const INITIATOR_USER
Definition: PageEditStash.php:78
MediaWiki\User\UserEditTracker
Track info about user edit counts and timings.
Definition: UserEditTracker.php:21
MediaWiki\Storage\PageEditStash\ERROR_BUSY
const ERROR_BUSY
Definition: PageEditStash.php:70
MediaWiki\Storage\PageEditStash\ERROR_UNCACHEABLE
const ERROR_UNCACHEABLE
Definition: PageEditStash.php:69
MediaWiki\HookContainer\HookContainer
HookContainer class.
Definition: HookContainer.php:45
MediaWiki\Storage\PageEditStash\$lb
ILoadBalancer $lb
Definition: PageEditStash.php:52
MediaWiki\HookContainer\HookRunner
This class provides an implementation of the core hook interfaces, forwarding hook calls to HookConta...
Definition: HookRunner.php:554
MediaWiki\Storage\PageEditStash\recentStashEntryCount
recentStashEntryCount(UserIdentity $user)
Definition: PageEditStash.php:520
MediaWiki\Storage\PageEditStash\MAX_SIGNATURE_TTL
const MAX_SIGNATURE_TTL
Definition: PageEditStash.php:74
CacheTime\getCacheTime
getCacheTime()
Definition: CacheTime.php:65
MediaWiki\Storage\PageEditStash\MAX_CACHE_RECENT
const MAX_CACHE_RECENT
Definition: PageEditStash.php:76
MediaWiki\Storage\PageEditStash\INITIATOR_JOB_OR_CLI
const INITIATOR_JOB_OR_CLI
Definition: PageEditStash.php:79
MediaWiki\Storage\PageEditStash\MAX_CACHE_TTL
const MAX_CACHE_TTL
Definition: PageEditStash.php:73
MediaWiki\Storage\PageEditStash\parseAndCache
parseAndCache(WikiPage $page, Content $content, UserIdentity $user, string $summary)
Definition: PageEditStash.php:118
MediaWiki\User\UserFactory
Creates User objects.
Definition: UserFactory.php:41
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:81
MediaWiki\Storage\PageEditStash\$cache
BagOStuff $cache
Definition: PageEditStash.php:50
MediaWiki\Storage\PageEditStash\ERROR_NONE
const ERROR_NONE
Definition: PageEditStash.php:66