MediaWiki  master
CategoryMembershipChangeJob.php
Go to the documentation of this file.
1 <?php
27 
43  private $ticket;
44 
45  private const ENQUEUE_FUDGE_SEC = 60;
46 
52  public static function newSpec( Title $title, $revisionTimestamp ) {
53  return new JobSpecification(
54  'categoryMembershipChange',
55  [
56  'pageId' => $title->getArticleID(),
57  'revTimestamp' => $revisionTimestamp,
58  ],
59  [
60  'removeDuplicates' => true,
61  'removeDuplicatesIgnoreParams' => [ 'revTimestamp' ]
62  ],
63  $title
64  );
65  }
66 
73  public function __construct( Title $title, array $params ) {
74  parent::__construct( 'categoryMembershipChange', $title, $params );
75  // Only need one job per page. Note that ENQUEUE_FUDGE_SEC handles races where an
76  // older revision job gets inserted while the newer revision job is de-duplicated.
77  $this->removeDuplicates = true;
78  }
79 
80  public function run() {
81  $services = MediaWikiServices::getInstance();
82  $lbFactory = $services->getDBLoadBalancerFactory();
83  $lb = $lbFactory->getMainLB();
84  $dbw = $lb->getConnectionRef( DB_MASTER );
85 
86  $this->ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
87 
88  $page = $services->getWikiPageFactory()->newFromID( $this->params['pageId'], WikiPage::READ_LATEST );
89  if ( !$page ) {
90  $this->setLastError( "Could not find page #{$this->params['pageId']}" );
91  return false; // deleted?
92  }
93 
94  // Cut down on the time spent in waitForMasterPos() in the critical section
95  $dbr = $lb->getConnectionRef( DB_REPLICA, [ 'recentchanges' ] );
96  if ( !$lb->waitForMasterPos( $dbr ) ) {
97  $this->setLastError( "Timed out while pre-waiting for replica DB to catch up" );
98  return false;
99  }
100 
101  // Use a named lock so that jobs for this page see each others' changes
102  $lockKey = "{$dbw->getDomainID()}:CategoryMembershipChange:{$page->getId()}"; // per-wiki
103  $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 3 );
104  if ( !$scopedLock ) {
105  $this->setLastError( "Could not acquire lock '$lockKey'" );
106  return false;
107  }
108 
109  // Wait till replica DB is caught up so that jobs for this page see each others' changes
110  if ( !$lb->waitForMasterPos( $dbr ) ) {
111  $this->setLastError( "Timed out while waiting for replica DB to catch up" );
112  return false;
113  }
114  // Clear any stale REPEATABLE-READ snapshot
115  $dbr->flushSnapshot( __METHOD__ );
116 
117  $cutoffUnix = wfTimestamp( TS_UNIX, $this->params['revTimestamp'] );
118  // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
119  // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
120  $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
121 
122  // Get the newest page revision that has a SRC_CATEGORIZE row.
123  // Assume that category changes before it were already handled.
124  $row = $dbr->selectRow(
125  'revision',
126  [ 'rev_timestamp', 'rev_id' ],
127  [
128  'rev_page' => $page->getId(),
129  'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) ),
130  'EXISTS (' . $dbr->selectSQLText(
131  'recentchanges',
132  '1',
133  [
134  'rc_this_oldid = rev_id',
135  'rc_source' => RecentChange::SRC_CATEGORIZE,
136  ],
137  __METHOD__
138  ) . ')'
139  ],
140  __METHOD__,
141  [ 'ORDER BY' => [ 'rev_timestamp DESC', 'rev_id DESC' ] ]
142  );
143  // Only consider revisions newer than any such revision
144  if ( $row ) {
145  $cutoffUnix = wfTimestamp( TS_UNIX, $row->rev_timestamp );
146  $lastRevId = (int)$row->rev_id;
147  } else {
148  $lastRevId = 0;
149  }
150 
151  // Find revisions to this page made around and after this revision which lack category
152  // notifications in recent changes. This lets jobs pick up were the last one left off.
153  $encCutoff = $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) );
154  $revisionStore = $services->getRevisionStore();
155  $revQuery = $revisionStore->getQueryInfo();
156  $res = $dbr->select(
157  $revQuery['tables'],
158  $revQuery['fields'],
159  [
160  'rev_page' => $page->getId(),
161  "rev_timestamp > $encCutoff" .
162  " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
163  ],
164  __METHOD__,
165  [ 'ORDER BY' => [ 'rev_timestamp ASC', 'rev_id ASC' ] ],
166  $revQuery['joins']
167  );
168 
169  // Apply all category updates in revision timestamp order
170  foreach ( $res as $row ) {
171  $this->notifyUpdatesForRevision( $lbFactory, $page, $revisionStore->newRevisionFromRow( $row ) );
172  }
173 
174  return true;
175  }
176 
183  protected function notifyUpdatesForRevision(
184  LBFactory $lbFactory, WikiPage $page, RevisionRecord $newRev
185  ) {
186  $config = RequestContext::getMain()->getConfig();
187  $title = $page->getTitle();
188 
189  // Get the new revision
190  if ( $newRev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
191  return;
192  }
193 
194  // Get the prior revision (the same for null edits)
195  if ( $newRev->getParentId() ) {
196  $oldRev = MediaWikiServices::getInstance()
197  ->getRevisionLookup()
198  ->getRevisionById( $newRev->getParentId(), RevisionLookup::READ_LATEST );
199  if ( !$oldRev || $oldRev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
200  return;
201  }
202  } else {
203  $oldRev = null;
204  }
205 
206  // Parse the new revision and get the categories
207  $categoryChanges = $this->getExplicitCategoriesChanges( $page, $newRev, $oldRev );
208  list( $categoryInserts, $categoryDeletes ) = $categoryChanges;
209  if ( !$categoryInserts && !$categoryDeletes ) {
210  return; // nothing to do
211  }
212 
213  $catMembChange = new CategoryMembershipChange( $title, $newRev );
214  $catMembChange->checkTemplateLinks();
215 
216  $batchSize = $config->get( 'UpdateRowsPerQuery' );
217  $insertCount = 0;
218 
219  foreach ( $categoryInserts as $categoryName ) {
220  $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
221  $catMembChange->triggerCategoryAddedNotification( $categoryTitle );
222  if ( $insertCount++ && ( $insertCount % $batchSize ) == 0 ) {
223  $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
224  }
225  }
226 
227  foreach ( $categoryDeletes as $categoryName ) {
228  $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
229  $catMembChange->triggerCategoryRemovedNotification( $categoryTitle );
230  if ( $insertCount++ && ( $insertCount++ % $batchSize ) == 0 ) {
231  $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
232  }
233  }
234  }
235 
237  WikiPage $page, RevisionRecord $newRev, RevisionRecord $oldRev = null
238  ) {
239  // Inject the same timestamp for both revision parses to avoid seeing category changes
240  // due to time-based parser functions. Inject the same page title for the parses too.
241  // Note that REPEATABLE-READ makes template/file pages appear unchanged between parses.
242  $parseTimestamp = $newRev->getTimestamp();
243  // Parse the old rev and get the categories. Do not use link tables as that
244  // assumes these updates are perfectly FIFO and that link tables are always
245  // up to date, neither of which are true.
246  $oldCategories = $oldRev
247  ? $this->getCategoriesAtRev( $page, $oldRev, $parseTimestamp )
248  : [];
249  // Parse the new revision and get the categories
250  $newCategories = $this->getCategoriesAtRev( $page, $newRev, $parseTimestamp );
251 
252  $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
253  $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
254 
255  return [ $categoryInserts, $categoryDeletes ];
256  }
257 
265  private function getCategoriesAtRev( WikiPage $page, RevisionRecord $rev, $parseTimestamp ) {
266  $services = MediaWikiServices::getInstance();
267  $options = $page->makeParserOptions( 'canonical' );
268  $options->setTimestamp( $parseTimestamp );
269 
270  $output = $rev instanceof RevisionStoreRecord && $rev->isCurrent()
271  ? $services->getParserCache()->get( $page, $options )
272  : null;
273 
274  if ( !$output || $output->getCacheRevisionId() !== $rev->getId() ) {
275  $output = $services->getRevisionRenderer()->getRenderedRevision( $rev, $options )
276  ->getRevisionParserOutput();
277  }
278 
279  // array keys will cast numeric category names to ints
280  // so we need to cast them back to strings to avoid breaking things!
281  return array_map( 'strval', array_keys( $output->getCategories() ) );
282  }
283 
284  public function getDeduplicationInfo() {
285  $info = parent::getDeduplicationInfo();
286  unset( $info['params']['revTimestamp'] ); // first job wins
287 
288  return $info;
289  }
290 }
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:46
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:166
Revision\RevisionRecord\isDeleted
isDeleted( $field)
MCR migration note: this replaces Revision::isDeleted.
Definition: RevisionRecord.php:412
CategoryMembershipChangeJob\notifyUpdatesForRevision
notifyUpdatesForRevision(LBFactory $lbFactory, WikiPage $page, RevisionRecord $newRev)
Definition: CategoryMembershipChangeJob.php:183
Wikimedia\Rdbms\LBFactory\commitAndWaitForReplication
commitAndWaitForReplication( $fname, $ticket, array $opts=[])
Convenience method for safely running commitMasterChanges()/waitForReplication()
Definition: LBFactory.php:510
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1831
Job\$title
Title $title
Definition: Job.php:46
Revision\RevisionRecord\getTimestamp
getTimestamp()
MCR migration note: this replaces Revision::getTimestamp.
Definition: RevisionRecord.php:434
CategoryMembershipChangeJob\getCategoriesAtRev
getCategoriesAtRev(WikiPage $page, RevisionRecord $rev, $parseTimestamp)
Definition: CategoryMembershipChangeJob.php:265
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:55
Title\getArticleID
getArticleID( $flags=0)
Get the article ID for this Title from the link cache, adding it if necessary.
Definition: Title.php:3180
WikiPage\makeParserOptions
makeParserOptions( $context)
Get parser options suitable for rendering the primary article wikitext.
Definition: WikiPage.php:2072
RecentChange\SRC_CATEGORIZE
const SRC_CATEGORIZE
Definition: RecentChange.php:81
$res
$res
Definition: testCompression.php:57
CategoryMembershipChangeJob\getDeduplicationInfo
getDeduplicationInfo()
Subclasses may need to override this to make duplication detection work.
Definition: CategoryMembershipChangeJob.php:284
Job\$params
array $params
Array of job parameters.
Definition: Job.php:40
$revQuery
$revQuery
Definition: testCompression.php:56
Job\setLastError
setLastError( $error)
Definition: Job.php:464
Revision\RevisionLookup
Service for looking up page revisions.
Definition: RevisionLookup.php:38
$dbr
$dbr
Definition: testCompression.php:54
Job
Class to both describe a background job and handle jobs.
Definition: Job.php:35
WikiPage\getTitle
getTitle()
Get the title object of the article.
Definition: WikiPage.php:285
CategoryMembershipChangeJob\run
run()
Run the job.
Definition: CategoryMembershipChangeJob.php:80
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:624
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
CategoryMembershipChangeJob
Job to add recent change entries mentioning category membership changes.
Definition: CategoryMembershipChangeJob.php:41
Revision\RevisionRecord\getId
getId()
Get revision ID.
Definition: RevisionRecord.php:271
Revision\RevisionRecord\getParentId
getParentId()
Get parent revision ID (the original previous page revision).
Definition: RevisionRecord.php:287
CategoryMembershipChangeJob\$ticket
int null $ticket
Definition: CategoryMembershipChangeJob.php:43
Revision\RevisionStoreRecord
A RevisionRecord representing an existing revision persisted in the revision table.
Definition: RevisionStoreRecord.php:40
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:454
Title
Represents a title within MediaWiki.
Definition: Title.php:46
JobSpecification
Job queue task description base code.
Definition: JobSpecification.php:39
Wikimedia\Rdbms\LBFactory
An interface for generating database load balancers.
Definition: LBFactory.php:41
CategoryMembershipChangeJob\ENQUEUE_FUDGE_SEC
const ENQUEUE_FUDGE_SEC
Definition: CategoryMembershipChangeJob.php:45
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:77
CategoryMembershipChangeJob\getExplicitCategoriesChanges
getExplicitCategoriesChanges(WikiPage $page, RevisionRecord $newRev, RevisionRecord $oldRev=null)
Definition: CategoryMembershipChangeJob.php:236
CategoryMembershipChangeJob\newSpec
static newSpec(Title $title, $revisionTimestamp)
Definition: CategoryMembershipChangeJob.php:52
Revision\RevisionRecord\isCurrent
isCurrent()
Checks whether the revision record is a stored current revision.
Definition: RevisionRecord.php:574
CategoryMembershipChange
Definition: CategoryMembershipChange.php:31
CategoryMembershipChangeJob\__construct
__construct(Title $title, array $params)
Constructor for use by the Job Queue infrastructure.
Definition: CategoryMembershipChangeJob.php:73