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