3 * Updater for link tracking tables after a page edit.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 use MediaWiki\MediaWikiServices
;
23 use Wikimedia\Rdbms\LBFactory
;
26 * Job to add recent change entries mentioning category membership changes
28 * This allows users to easily scan categories for recent page membership changes
32 * - revTimestamp : timestamp of the triggering revision
34 * Category changes will be mentioned for revisions at/after the timestamp for this page
38 class CategoryMembershipChangeJob
extends Job
{
42 const ENQUEUE_FUDGE_SEC
= 60;
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;
51 public function run() {
52 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
53 $lb = $lbFactory->getMainLB();
54 $dbw = $lb->getConnection( DB_MASTER
);
56 $this->ticket
= $lbFactory->getEmptyTransactionTicket( __METHOD__
);
58 $page = WikiPage
::newFromID( $this->params
['pageId'], WikiPage
::READ_LATEST
);
60 $this->setLastError( "Could not find page #{$this->params['pageId']}" );
61 return false; // deleted?
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" );
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 );
75 $this->setLastError( "Could not acquire lock '$lockKey'" );
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" );
84 // Clear any stale REPEATABLE-READ snapshot
85 $dbr->flushSnapshot( __METHOD__
);
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
;
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(
96 [ 'rev_timestamp', 'rev_id' ],
98 'rev_page' => $page->getId(),
99 'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) ),
100 'EXISTS (' . $dbr->selectSQLText(
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'
113 [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC' ]
115 // Only consider revisions newer than any such revision
117 $cutoffUnix = wfTimestamp( TS_UNIX
, $row->rev_timestamp
);
118 $lastRevId = (int)$row->rev_id
;
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 ) );
126 $revQuery = Revision
::getQueryInfo();
131 'rev_page' => $page->getId(),
132 "rev_timestamp > $encCutoff" .
133 " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
136 [ 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC' ],
140 // Apply all category updates in revision timestamp order
141 foreach ( $res as $row ) {
142 $this->notifyUpdatesForRevision( $lbFactory, $page, Revision
::newFromRow( $row ) );
149 * @param LBFactory $lbFactory
150 * @param WikiPage $page
151 * @param Revision $newRev
152 * @throws MWException
154 protected function notifyUpdatesForRevision(
155 LBFactory
$lbFactory, WikiPage
$page, Revision
$newRev
157 $config = RequestContext
::getMain()->getConfig();
158 $title = $page->getTitle();
160 // Get the new revision
161 if ( !$newRev->getContent() ) {
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() ) {
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
182 $catMembChange = new CategoryMembershipChange( $title, $newRev );
183 $catMembChange->checkTemplateLinks();
185 $batchSize = $config->get( 'UpdateRowsPerQuery' );
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
);
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
);
205 private function getExplicitCategoriesChanges(
206 Title
$title, Revision
$newRev, Revision
$oldRev = null
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 )
218 // Parse the new revision and get the categories
219 $newCategories = $this->getCategoriesAtRev( $title, $newRev, $parseTimestamp );
221 $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
222 $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
224 return [ $categoryInserts, $categoryDeletes ];
228 * @param Title $title
229 * @param Revision $rev
230 * @param string $parseTimestamp TS_MW
232 * @return string[] category names
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 );
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() ) );
247 public function getDeduplicationInfo() {
248 $info = parent
::getDeduplicationInfo();
249 unset( $info['params']['revTimestamp'] ); // first job wins