MediaWiki  REL1_31
CategoryMembershipChangeJob.php
Go to the documentation of this file.
1 <?php
24 
40  private $ticket;
41 
42  const ENQUEUE_FUDGE_SEC = 60;
43 
44  public function __construct( Title $title, array $params ) {
45  parent::__construct( 'categoryMembershipChange', $title, $params );
46  // Only need one job per page. Note that ENQUEUE_FUDGE_SEC handles races where an
47  // older revision job gets inserted while the newer revision job is de-duplicated.
48  $this->removeDuplicates = true;
49  }
50 
51  public function run() {
52  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
53  $lb = $lbFactory->getMainLB();
54  $dbw = $lb->getConnection( DB_MASTER );
55 
56  $this->ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
57 
58  $page = WikiPage::newFromID( $this->params['pageId'], WikiPage::READ_LATEST );
59  if ( !$page ) {
60  $this->setLastError( "Could not find page #{$this->params['pageId']}" );
61  return false; // deleted?
62  }
63 
64  // Cut down on the time spent in safeWaitForMasterPos() in the critical section
65  $dbr = $lb->getConnection( DB_REPLICA, [ 'recentchanges' ] );
66  if ( !$lb->safeWaitForMasterPos( $dbr ) ) {
67  $this->setLastError( "Timed out while pre-waiting for replica DB to catch up" );
68  return false;
69  }
70 
71  // Use a named lock so that jobs for this page see each others' changes
72  $lockKey = "CategoryMembershipUpdates:{$page->getId()}";
73  $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 3 );
74  if ( !$scopedLock ) {
75  $this->setLastError( "Could not acquire lock '$lockKey'" );
76  return false;
77  }
78 
79  // Wait till replica DB is caught up so that jobs for this page see each others' changes
80  if ( !$lb->safeWaitForMasterPos( $dbr ) ) {
81  $this->setLastError( "Timed out while waiting for replica DB to catch up" );
82  return false;
83  }
84  // Clear any stale REPEATABLE-READ snapshot
85  $dbr->flushSnapshot( __METHOD__ );
86 
87  $cutoffUnix = wfTimestamp( TS_UNIX, $this->params['revTimestamp'] );
88  // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
89  // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
90  $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
91 
92  // Get the newest page revision that has a SRC_CATEGORIZE row.
93  // Assume that category changes before it were already handled.
94  $row = $dbr->selectRow(
95  'revision',
96  [ 'rev_timestamp', 'rev_id' ],
97  [
98  'rev_page' => $page->getId(),
99  'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) ),
100  'EXISTS (' . $dbr->selectSQLText(
101  'recentchanges',
102  '1',
103  [
104  'rc_this_oldid = rev_id',
105  'rc_source' => RecentChange::SRC_CATEGORIZE,
106  // Allow rc_cur_id or rc_timestamp index usage
107  'rc_cur_id = rev_page',
108  'rc_timestamp = rev_timestamp'
109  ]
110  ) . ')'
111  ],
112  __METHOD__,
113  [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC' ]
114  );
115  // Only consider revisions newer than any such revision
116  if ( $row ) {
117  $cutoffUnix = wfTimestamp( TS_UNIX, $row->rev_timestamp );
118  $lastRevId = (int)$row->rev_id;
119  } else {
120  $lastRevId = 0;
121  }
122 
123  // Find revisions to this page made around and after this revision which lack category
124  // notifications in recent changes. This lets jobs pick up were the last one left off.
125  $encCutoff = $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) );
127  $res = $dbr->select(
128  $revQuery['tables'],
129  $revQuery['fields'],
130  [
131  'rev_page' => $page->getId(),
132  "rev_timestamp > $encCutoff" .
133  " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
134  ],
135  __METHOD__,
136  [ 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC' ],
137  $revQuery['joins']
138  );
139 
140  // Apply all category updates in revision timestamp order
141  foreach ( $res as $row ) {
142  $this->notifyUpdatesForRevision( $lbFactory, $page, Revision::newFromRow( $row ) );
143  }
144 
145  return true;
146  }
147 
154  protected function notifyUpdatesForRevision(
155  LBFactory $lbFactory, WikiPage $page, Revision $newRev
156  ) {
157  $config = RequestContext::getMain()->getConfig();
158  $title = $page->getTitle();
159 
160  // Get the new revision
161  if ( !$newRev->getContent() ) {
162  return; // deleted?
163  }
164 
165  // Get the prior revision (the same for null edits)
166  if ( $newRev->getParentId() ) {
167  $oldRev = Revision::newFromId( $newRev->getParentId(), Revision::READ_LATEST );
168  if ( !$oldRev->getContent() ) {
169  return; // deleted?
170  }
171  } else {
172  $oldRev = null;
173  }
174 
175  // Parse the new revision and get the categories
176  $categoryChanges = $this->getExplicitCategoriesChanges( $title, $newRev, $oldRev );
177  list( $categoryInserts, $categoryDeletes ) = $categoryChanges;
178  if ( !$categoryInserts && !$categoryDeletes ) {
179  return; // nothing to do
180  }
181 
182  $catMembChange = new CategoryMembershipChange( $title, $newRev );
183  $catMembChange->checkTemplateLinks();
184 
185  $batchSize = $config->get( 'UpdateRowsPerQuery' );
186  $insertCount = 0;
187 
188  foreach ( $categoryInserts as $categoryName ) {
189  $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
190  $catMembChange->triggerCategoryAddedNotification( $categoryTitle );
191  if ( $insertCount++ && ( $insertCount % $batchSize ) == 0 ) {
192  $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
193  }
194  }
195 
196  foreach ( $categoryDeletes as $categoryName ) {
197  $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
198  $catMembChange->triggerCategoryRemovedNotification( $categoryTitle );
199  if ( $insertCount++ && ( $insertCount++ % $batchSize ) == 0 ) {
200  $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
201  }
202  }
203  }
204 
206  Title $title, Revision $newRev, Revision $oldRev = null
207  ) {
208  // Inject the same timestamp for both revision parses to avoid seeing category changes
209  // due to time-based parser functions. Inject the same page title for the parses too.
210  // Note that REPEATABLE-READ makes template/file pages appear unchanged between parses.
211  $parseTimestamp = $newRev->getTimestamp();
212  // Parse the old rev and get the categories. Do not use link tables as that
213  // assumes these updates are perfectly FIFO and that link tables are always
214  // up to date, neither of which are true.
215  $oldCategories = $oldRev
216  ? $this->getCategoriesAtRev( $title, $oldRev, $parseTimestamp )
217  : [];
218  // Parse the new revision and get the categories
219  $newCategories = $this->getCategoriesAtRev( $title, $newRev, $parseTimestamp );
220 
221  $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
222  $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
223 
224  return [ $categoryInserts, $categoryDeletes ];
225  }
226 
234  private function getCategoriesAtRev( Title $title, Revision $rev, $parseTimestamp ) {
235  $content = $rev->getContent();
236  $options = $content->getContentHandler()->makeParserOptions( 'canonical' );
237  $options->setTimestamp( $parseTimestamp );
238  // This could possibly use the parser cache if it checked the revision ID,
239  // but that's more complicated than it's worth.
240  $output = $content->getParserOutput( $title, $rev->getId(), $options );
241 
242  // array keys will cast numeric category names to ints
243  // so we need to cast them back to strings to avoid breaking things!
244  return array_map( 'strval', array_keys( $output->getCategories() ) );
245  }
246 
247  public function getDeduplicationInfo() {
248  $info = parent::getDeduplicationInfo();
249  unset( $info['params']['revTimestamp'] ); // first job wins
250 
251  return $info;
252  }
253 }
Revision\getTimestamp
getTimestamp()
Definition: Revision.php:1008
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
Revision\newFromId
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:114
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$output
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2255
Wikimedia\Rdbms\LBFactory\commitAndWaitForReplication
commitAndWaitForReplication( $fname, $ticket, array $opts=[])
Convenience method for safely running commitMasterChanges()/waitForReplication()
Definition: LBFactory.php:411
Revision\getContent
getContent( $audience=self::FOR_PUBLIC, User $user=null)
Fetch revision content if it's available to the specified audience.
Definition: Revision.php:929
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1980
Job\$title
Title $title
Definition: Job.php:42
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:37
Revision\getParentId
getParentId()
Get parent revision ID (the original previous page revision)
Definition: Revision.php:696
$res
$res
Definition: database.txt:21
RecentChange\SRC_CATEGORIZE
const SRC_CATEGORIZE
Definition: RecentChange.php:75
CategoryMembershipChangeJob\getDeduplicationInfo
getDeduplicationInfo()
Subclasses may need to override this to make duplication detection work.
Definition: CategoryMembershipChangeJob.php:247
Job\$params
array $params
Array of job parameters.
Definition: Job.php:36
$revQuery
$revQuery
Definition: testCompression.php:51
Job\setLastError
setLastError( $error)
Definition: Job.php:419
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:37
$dbr
$dbr
Definition: testCompression.php:50
Revision
Definition: Revision.php:41
Job
Class to both describe a background job and handle jobs.
Definition: Job.php:31
Revision\getQueryInfo
static getQueryInfo( $options=[])
Return the tables, fields, and join conditions to be selected to create a new revision object.
Definition: Revision.php:492
CategoryMembershipChangeJob\getExplicitCategoriesChanges
getExplicitCategoriesChanges(Title $title, Revision $newRev, Revision $oldRev=null)
Definition: CategoryMembershipChangeJob.php:205
WikiPage\getTitle
getTitle()
Get the title object of the article.
Definition: WikiPage.php:236
CategoryMembershipChangeJob\run
run()
Run the job.
Definition: CategoryMembershipChangeJob.php:51
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:534
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:88
DB_MASTER
const DB_MASTER
Definition: defines.php:29
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
CategoryMembershipChangeJob
Job to add recent change entries mentioning category membership changes.
Definition: CategoryMembershipChangeJob.php:38
$options
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:2001
WikiPage\newFromID
static newFromID( $id, $from='fromdb')
Constructor from a page id.
Definition: WikiPage.php:153
CategoryMembershipChangeJob\$ticket
int null $ticket
Definition: CategoryMembershipChangeJob.php:40
Revision\newFromRow
static newFromRow( $row)
Definition: Revision.php:218
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:434
$rev
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition: hooks.txt:1777
Title
Represents a title within MediaWiki.
Definition: Title.php:39
Wikimedia\Rdbms\LBFactory
An interface for generating database load balancers.
Definition: LBFactory.php:39
CategoryMembershipChangeJob\ENQUEUE_FUDGE_SEC
const ENQUEUE_FUDGE_SEC
Definition: CategoryMembershipChangeJob.php:42
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:22
CategoryMembershipChangeJob\notifyUpdatesForRevision
notifyUpdatesForRevision(LBFactory $lbFactory, WikiPage $page, Revision $newRev)
Definition: CategoryMembershipChangeJob.php:154
CategoryMembershipChangeJob\getCategoriesAtRev
getCategoriesAtRev(Title $title, Revision $rev, $parseTimestamp)
Definition: CategoryMembershipChangeJob.php:234
CategoryMembershipChange
Definition: CategoryMembershipChange.php:28
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:25
CategoryMembershipChangeJob\__construct
__construct(Title $title, array $params)
Definition: CategoryMembershipChangeJob.php:44