1c7647c28fbf5ca0a1e93b4636ed06e3074929f3
[lhc/web/wiklou.git] / includes / jobqueue / jobs / CategoryMembershipChangeJob.php
1 <?php
2 /**
3 * Updater for link tracking tables after a page edit.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22 use MediaWiki\MediaWikiServices;
23 use Wikimedia\Rdbms\LBFactory;
24
25 /**
26 * Job to add recent change entries mentioning category membership changes
27 *
28 * This allows users to easily scan categories for recent page membership changes
29 *
30 * Parameters include:
31 * - pageId : page ID
32 * - revTimestamp : timestamp of the triggering revision
33 *
34 * Category changes will be mentioned for revisions at/after the timestamp for this page
35 *
36 * @since 1.27
37 */
38 class CategoryMembershipChangeJob extends Job {
39 /** @var int|null */
40 private $ticket;
41
42 const ENQUEUE_FUDGE_SEC = 60;
43
44 /**
45 * @var ParserCache
46 */
47 private $parserCache;
48
49 /**
50 * @param Title $title The title of the page for which to update category emmbership.
51 * @param string $revisionTimestamp The timestamp of the new revision that triggered the job.
52 * @return JobSpecification
53 */
54 public static function newSpec( Title $title, $revisionTimestamp ) {
55 return new JobSpecification(
56 'categoryMembershipChange',
57 [
58 'pageId' => $title->getArticleID(),
59 'revTimestamp' => $revisionTimestamp,
60 ],
61 [],
62 $title
63 );
64 }
65
66 /**
67 * Constructor for use by the Job Queue infrastructure.
68 * @note Don't call this when queueing a new instance, use newSpec() instead.
69 */
70 public function __construct( ParserCache $parserCache, Title $title, array $params ) {
71 parent::__construct( 'categoryMembershipChange', $title, $params );
72 // Only need one job per page. Note that ENQUEUE_FUDGE_SEC handles races where an
73 // older revision job gets inserted while the newer revision job is de-duplicated.
74 $this->removeDuplicates = true;
75 $this->parserCache = $parserCache;
76 }
77
78 public function run() {
79 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
80 $lb = $lbFactory->getMainLB();
81 $dbw = $lb->getConnection( DB_MASTER );
82
83 $this->ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
84
85 $page = WikiPage::newFromID( $this->params['pageId'], WikiPage::READ_LATEST );
86 if ( !$page ) {
87 $this->setLastError( "Could not find page #{$this->params['pageId']}" );
88 return false; // deleted?
89 }
90
91 // Cut down on the time spent in safeWaitForMasterPos() in the critical section
92 $dbr = $lb->getConnection( DB_REPLICA, [ 'recentchanges' ] );
93 if ( !$lb->safeWaitForMasterPos( $dbr ) ) {
94 $this->setLastError( "Timed out while pre-waiting for replica DB to catch up" );
95 return false;
96 }
97
98 // Use a named lock so that jobs for this page see each others' changes
99 $lockKey = "CategoryMembershipUpdates:{$page->getId()}";
100 $scopedLock = $dbw->getScopedLockAndFlush( $lockKey, __METHOD__, 3 );
101 if ( !$scopedLock ) {
102 $this->setLastError( "Could not acquire lock '$lockKey'" );
103 return false;
104 }
105
106 // Wait till replica DB is caught up so that jobs for this page see each others' changes
107 if ( !$lb->safeWaitForMasterPos( $dbr ) ) {
108 $this->setLastError( "Timed out while waiting for replica DB to catch up" );
109 return false;
110 }
111 // Clear any stale REPEATABLE-READ snapshot
112 $dbr->flushSnapshot( __METHOD__ );
113
114 $cutoffUnix = wfTimestamp( TS_UNIX, $this->params['revTimestamp'] );
115 // Using ENQUEUE_FUDGE_SEC handles jobs inserted out of revision order due to the delay
116 // between COMMIT and actual enqueueing of the CategoryMembershipChangeJob job.
117 $cutoffUnix -= self::ENQUEUE_FUDGE_SEC;
118
119 // Get the newest page revision that has a SRC_CATEGORIZE row.
120 // Assume that category changes before it were already handled.
121 $row = $dbr->selectRow(
122 'revision',
123 [ 'rev_timestamp', 'rev_id' ],
124 [
125 'rev_page' => $page->getId(),
126 'rev_timestamp >= ' . $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) ),
127 'EXISTS (' . $dbr->selectSQLText(
128 'recentchanges',
129 '1',
130 [
131 'rc_this_oldid = rev_id',
132 'rc_source' => RecentChange::SRC_CATEGORIZE,
133 // Allow rc_cur_id or rc_timestamp index usage
134 'rc_cur_id = rev_page',
135 'rc_timestamp = rev_timestamp'
136 ]
137 ) . ')'
138 ],
139 __METHOD__,
140 [ 'ORDER BY' => 'rev_timestamp DESC, rev_id DESC' ]
141 );
142 // Only consider revisions newer than any such revision
143 if ( $row ) {
144 $cutoffUnix = wfTimestamp( TS_UNIX, $row->rev_timestamp );
145 $lastRevId = (int)$row->rev_id;
146 } else {
147 $lastRevId = 0;
148 }
149
150 // Find revisions to this page made around and after this revision which lack category
151 // notifications in recent changes. This lets jobs pick up were the last one left off.
152 $encCutoff = $dbr->addQuotes( $dbr->timestamp( $cutoffUnix ) );
153 $revQuery = Revision::getQueryInfo();
154 $res = $dbr->select(
155 $revQuery['tables'],
156 $revQuery['fields'],
157 [
158 'rev_page' => $page->getId(),
159 "rev_timestamp > $encCutoff" .
160 " OR (rev_timestamp = $encCutoff AND rev_id > $lastRevId)"
161 ],
162 __METHOD__,
163 [ 'ORDER BY' => 'rev_timestamp ASC, rev_id ASC' ],
164 $revQuery['joins']
165 );
166
167 // Apply all category updates in revision timestamp order
168 foreach ( $res as $row ) {
169 $this->notifyUpdatesForRevision( $lbFactory, $page, Revision::newFromRow( $row ) );
170 }
171
172 return true;
173 }
174
175 /**
176 * @param LBFactory $lbFactory
177 * @param WikiPage $page
178 * @param Revision $newRev
179 * @throws MWException
180 */
181 protected function notifyUpdatesForRevision(
182 LBFactory $lbFactory, WikiPage $page, Revision $newRev
183 ) {
184 $config = RequestContext::getMain()->getConfig();
185 $title = $page->getTitle();
186
187 // Get the new revision
188 if ( !$newRev->getContent() ) {
189 return; // deleted?
190 }
191
192 // Get the prior revision (the same for null edits)
193 if ( $newRev->getParentId() ) {
194 $oldRev = Revision::newFromId( $newRev->getParentId(), Revision::READ_LATEST );
195 if ( !$oldRev->getContent() ) {
196 return; // deleted?
197 }
198 } else {
199 $oldRev = null;
200 }
201
202 // Parse the new revision and get the categories
203 $categoryChanges = $this->getExplicitCategoriesChanges( $page, $newRev, $oldRev );
204 list( $categoryInserts, $categoryDeletes ) = $categoryChanges;
205 if ( !$categoryInserts && !$categoryDeletes ) {
206 return; // nothing to do
207 }
208
209 $catMembChange = new CategoryMembershipChange( $title, $newRev );
210 $catMembChange->checkTemplateLinks();
211
212 $batchSize = $config->get( 'UpdateRowsPerQuery' );
213 $insertCount = 0;
214
215 foreach ( $categoryInserts as $categoryName ) {
216 $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
217 $catMembChange->triggerCategoryAddedNotification( $categoryTitle );
218 if ( $insertCount++ && ( $insertCount % $batchSize ) == 0 ) {
219 $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
220 }
221 }
222
223 foreach ( $categoryDeletes as $categoryName ) {
224 $categoryTitle = Title::makeTitle( NS_CATEGORY, $categoryName );
225 $catMembChange->triggerCategoryRemovedNotification( $categoryTitle );
226 if ( $insertCount++ && ( $insertCount++ % $batchSize ) == 0 ) {
227 $lbFactory->commitAndWaitForReplication( __METHOD__, $this->ticket );
228 }
229 }
230 }
231
232 private function getExplicitCategoriesChanges(
233 WikiPage $page, Revision $newRev, Revision $oldRev = null
234 ) {
235 // Inject the same timestamp for both revision parses to avoid seeing category changes
236 // due to time-based parser functions. Inject the same page title for the parses too.
237 // Note that REPEATABLE-READ makes template/file pages appear unchanged between parses.
238 $parseTimestamp = $newRev->getTimestamp();
239 // Parse the old rev and get the categories. Do not use link tables as that
240 // assumes these updates are perfectly FIFO and that link tables are always
241 // up to date, neither of which are true.
242 $oldCategories = $oldRev
243 ? $this->getCategoriesAtRev( $page, $oldRev, $parseTimestamp )
244 : [];
245 // Parse the new revision and get the categories
246 $newCategories = $this->getCategoriesAtRev( $page, $newRev, $parseTimestamp );
247
248 $categoryInserts = array_values( array_diff( $newCategories, $oldCategories ) );
249 $categoryDeletes = array_values( array_diff( $oldCategories, $newCategories ) );
250
251 return [ $categoryInserts, $categoryDeletes ];
252 }
253
254 /**
255 * @param WikiPage $page
256 * @param Revision $rev
257 * @param string $parseTimestamp TS_MW
258 *
259 * @return string[] category names
260 */
261 private function getCategoriesAtRev( WikiPage $page, Revision $rev, $parseTimestamp ) {
262 $renderer = MediaWikiServices::getInstance()->getRevisionRenderer();
263 $options = $page->makeParserOptions( 'canonical' );
264 $options->setTimestamp( $parseTimestamp );
265
266 $output = $rev->isCurrent() ? $this->parserCache->get( $page, $options ) : null;
267
268 if ( !$output || $output->getCacheRevisionId() !== $rev->getId() ) {
269 $output = $renderer->getRenderedRevision( $rev->getRevisionRecord(), $options )
270 ->getRevisionParserOutput();
271 }
272
273 // array keys will cast numeric category names to ints
274 // so we need to cast them back to strings to avoid breaking things!
275 return array_map( 'strval', array_keys( $output->getCategories() ) );
276 }
277
278 public function getDeduplicationInfo() {
279 $info = parent::getDeduplicationInfo();
280 unset( $info['params']['revTimestamp'] ); // first job wins
281
282 return $info;
283 }
284 }