MediaWiki master
CategoryMembershipChangeJob.php
Go to the documentation of this file.
1<?php
31
48 private $ticket;
49
50 private const ENQUEUE_FUDGE_SEC = 60;
51
58 public static function newSpec( PageIdentity $page, $revisionTimestamp, bool $forImport ) {
59 return new JobSpecification(
60 'categoryMembershipChange',
61 [
62 'pageId' => $page->getId(),
63 'revTimestamp' => $revisionTimestamp,
64 'forImport' => $forImport,
65 ],
66 [
67 'removeDuplicates' => true,
68 'removeDuplicatesIgnoreParams' => [ 'revTimestamp' ]
69 ],
70 $page
71 );
72 }
73
80 public function __construct( PageIdentity $page, array $params ) {
81 parent::__construct( 'categoryMembershipChange', $page, $params );
82 // Only need one job per page. Note that ENQUEUE_FUDGE_SEC handles races where an
83 // older revision job gets inserted while the newer revision job is de-duplicated.
84 $this->removeDuplicates = true;
85 }
86
87 public function run() {
88 $services = MediaWikiServices::getInstance();
89 $lbFactory = $services->getDBLoadBalancerFactory();
90 $lb = $lbFactory->getMainLB();
91 $dbw = $lb->getConnection( DB_PRIMARY );
92
93 $this->ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
94
95 $page = $services->getWikiPageFactory()->newFromID( $this->params['pageId'], IDBAccessObject::READ_LATEST );
96 if ( !$page ) {
97 $this->setLastError( "Could not find page #{$this->params['pageId']}" );
98 return false; // deleted?
99 }
100
101 // Cut down on the time spent in waitForPrimaryPos() in the critical section
102 $dbr = $lb->getConnection( DB_REPLICA );
103 if ( !$lb->waitForPrimaryPos( $dbr ) ) {
104 $this->setLastError( "Timed out while pre-waiting for replica DB to catch up" );
105 return false;
106 }
107
108 // Use a named lock so that jobs for this page see each others' changes
109 $lockKey = "{$dbw->getDomainID()}:CategoryMembershipChange:{$page->getId()}"; // per-wiki
110 $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 3 );
111 if ( !$scopedLock ) {
112 $this->setLastError( "Could not acquire lock '$lockKey'" );
113 return false;
114 }
115
116 // Wait till replica DB is caught up so that jobs for this page see each others' changes
117 if ( !$lb->waitForPrimaryPos( $dbr ) ) {
118 $this->setLastError( "Timed out while waiting for replica DB to catch up" );
119 return false;
120 }
121 // Clear any stale REPEATABLE-READ snapshot
122 $dbr->flushSnapshot( __METHOD__ );
123
124 $cutoffUnix = wfTimestamp( TS_UNIX, $this->params['revTimestamp'] );
125 // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
126 // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
127 $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
128
129 // Get the newest page revision that has a SRC_CATEGORIZE row.
130 // Assume that category changes before it were already handled.
131 $subQuery = $dbr->newSelectQueryBuilder()
132 ->select( '1' )
133 ->from( 'recentchanges' )
134 ->where( 'rc_this_oldid = rev_id' )
135 ->andWhere( [ 'rc_source' => RecentChange::SRC_CATEGORIZE ] );
136 $row = $dbr->newSelectQueryBuilder()
137 ->select( [ 'rev_timestamp', 'rev_id' ] )
138 ->from( 'revision' )
139 ->where( [ 'rev_page' => $page->getId() ] )
140 ->andWhere( $dbr->expr( 'rev_timestamp', '>=', $dbr->timestamp( $cutoffUnix ) ) )
141 ->andWhere( new RawSQLExpression( 'EXISTS (' . $subQuery->getSQL() . ')' ) )
142 ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder::SORT_DESC )
143 ->caller( __METHOD__ )->fetchRow();
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 $revisionStore = $services->getRevisionStore();
156 $res = $revisionStore->newSelectQueryBuilder( $dbr )
157 ->joinComment()
158 ->where( [
159 'rev_page' => $page->getId(),
160 $dbr->buildComparison( '>', [
161 'rev_timestamp' => $dbr->timestamp( $cutoffUnix ),
162 'rev_id' => $lastRevId,
163 ] )
164 ] )
165 ->orderBy( [ 'rev_timestamp', 'rev_id' ], SelectQueryBuilder::SORT_ASC )
166 ->caller( __METHOD__ )->fetchResultSet();
167
168 // Apply all category updates in revision timestamp order
169 foreach ( $res as $row ) {
170 $this->notifyUpdatesForRevision( $lbFactory, $page, $revisionStore->newRevisionFromRow( $row ) );
171 }
172
173 return true;
174 }
175
181 protected function notifyUpdatesForRevision(
182 LBFactory $lbFactory, WikiPage $page, RevisionRecord $newRev
183 ) {
184 $title = $page->getTitle();
185
186 // Get the new revision
187 if ( $newRev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
188 return;
189 }
190
191 $services = MediaWikiServices::getInstance();
192 // Get the prior revision (the same for null edits)
193 if ( $newRev->getParentId() ) {
194 $oldRev = $services->getRevisionLookup()
195 ->getRevisionById( $newRev->getParentId(), IDBAccessObject::READ_LATEST );
196 if ( !$oldRev || $oldRev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
197 return;
198 }
199 } else {
200 $oldRev = null;
201 }
202
203 // Parse the new revision and get the categories
204 $categoryChanges = $this->getExplicitCategoriesChanges( $page, $newRev, $oldRev );
205 [ $categoryInserts, $categoryDeletes ] = $categoryChanges;
206 if ( !$categoryInserts && !$categoryDeletes ) {
207 return; // nothing to do
208 }
209
210 $blc = $services->getBacklinkCacheFactory()->getBacklinkCache( $title );
211 $catMembChange = new CategoryMembershipChange( $title, $blc, $newRev, $this->params['forImport'] ?? false );
212 $catMembChange->checkTemplateLinks();
213
214 $batchSize = $services->getMainConfig()->get( MainConfigNames::UpdateRowsPerQuery );
215 $insertCount = 0;
216
217 foreach ( $categoryInserts as $categoryName ) {
218 $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
219 $catMembChange->triggerCategoryAddedNotification( $categoryTitle );
220 if ( $insertCount++ && ( $insertCount % $batchSize ) == 0 ) {
221 $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
222 }
223 }
224
225 foreach ( $categoryDeletes as $categoryName ) {
226 $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
227 $catMembChange->triggerCategoryRemovedNotification( $categoryTitle );
228 if ( $insertCount++ && ( $insertCount++ % $batchSize ) == 0 ) {
229 $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
230 }
231 }
232 }
233
234 private function getExplicitCategoriesChanges(
235 WikiPage $page, RevisionRecord $newRev, RevisionRecord $oldRev = null
236 ) {
237 // Inject the same timestamp for both revision parses to avoid seeing category changes
238 // due to time-based parser functions. Inject the same page title for the parses too.
239 // Note that REPEATABLE-READ makes template/file pages appear unchanged between parses.
240 $parseTimestamp = $newRev->getTimestamp();
241 // Parse the old rev and get the categories. Do not use link tables as that
242 // assumes these updates are perfectly FIFO and that link tables are always
243 // up to date, neither of which are true.
244 $oldCategories = $oldRev
245 ? $this->getCategoriesAtRev( $page, $oldRev, $parseTimestamp )
246 : [];
247 // Parse the new revision and get the categories
248 $newCategories = $this->getCategoriesAtRev( $page, $newRev, $parseTimestamp );
249
250 $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
251 $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
252
253 return [ $categoryInserts, $categoryDeletes ];
254 }
255
263 private function getCategoriesAtRev( WikiPage $page, RevisionRecord $rev, $parseTimestamp ) {
264 $services = MediaWikiServices::getInstance();
265 $options = $page->makeParserOptions( 'canonical' );
266 $options->setTimestamp( $parseTimestamp );
267 $options->setRenderReason( 'CategoryMembershipChangeJob' );
268
269 $output = $rev instanceof RevisionStoreRecord && $rev->isCurrent()
270 ? $services->getParserCache()->get( $page, $options )
271 : null;
272
273 if ( !$output || $output->getCacheRevisionId() !== $rev->getId() ) {
274 $output = $services->getRevisionRenderer()->getRenderedRevision( $rev, $options )
275 ->getRevisionParserOutput();
276 }
277
278 // array keys will cast numeric category names to ints;
279 // ::getCategoryNames() is careful to cast them back to strings
280 // to avoid breaking things!
281 return $output->getCategoryNames();
282 }
283
284 public function getDeduplicationInfo() {
285 $info = parent::getDeduplicationInfo();
286 unset( $info['params']['revTimestamp'] ); // first job wins
287
288 return $info;
289 }
290}
const NS_CATEGORY
Definition Defines.php:79
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
array $params
The job parameters.
setLastError( $error)
This is actually implemented in the Job class.
Job to add recent change entries mentioning category membership changes.
static newSpec(PageIdentity $page, $revisionTimestamp, bool $forImport)
__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)
Helper class for category membership changes.
Job queue task description base code.
Describe and execute a background job.
Definition Job.php:41
Title $title
Definition Job.php:52
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.
Represents a title within MediaWiki.
Definition Title.php:78
Base representation for an editable wiki page.
Definition WikiPage.php:83
makeParserOptions( $context)
Get parser options suitable for rendering the primary article wikitext.
getId( $wikiId=self::LOCAL)
Definition WikiPage.php:533
getTitle()
Get the title object of the article.
Definition WikiPage.php:257
commitAndWaitForReplication( $fname, $ticket, array $opts=[])
Commit primary DB transactions and wait for replication (if $ticket indicates it is safe).
Raw SQL expression to be used in query builders.
Build SELECT queries with a fluent interface.
Interface for objects (potentially) representing an editable wiki page.
getId( $wikiId=self::LOCAL)
Returns the page ID.
Interface for database access objects.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28