Merge "Do not call the 'UploadStashFile' hook for partially uploaded files"
[lhc/web/wiklou.git] / includes / jobqueue / jobs / RefreshLinksJob.php
1 <?php
2 /**
3 * Job to update link tables for pages
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 * @ingroup JobQueue
22 */
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * Job to update link tables for pages
27 *
28 * This job comes in a few variants:
29 * - a) Recursive jobs to update links for backlink pages for a given title.
30 * These jobs have (recursive:true,table:<table>) set.
31 * - b) Jobs to update links for a set of pages (the job title is ignored).
32 * These jobs have (pages:(<page ID>:(<namespace>,<title>),...) set.
33 * - c) Jobs to update links for a single page (the job title)
34 * These jobs need no extra fields set.
35 *
36 * @ingroup JobQueue
37 */
38 class RefreshLinksJob extends Job {
39 /** @var float Cache parser output when it takes this long to render */
40 const PARSE_THRESHOLD_SEC = 1.0;
41 /** @var integer Lag safety margin when comparing root job times to last-refresh times */
42 const CLOCK_FUDGE = 10;
43 /** @var integer How many seconds to wait for slaves to catch up */
44 const LAG_WAIT_TIMEOUT = 15;
45
46 function __construct( Title $title, array $params ) {
47 parent::__construct( 'refreshLinks', $title, $params );
48 // Avoid the overhead of de-duplication when it would be pointless
49 $this->removeDuplicates = (
50 // Ranges rarely will line up
51 !isset( $params['range'] ) &&
52 // Multiple pages per job make matches unlikely
53 !( isset( $params['pages'] ) && count( $params['pages'] ) != 1 )
54 );
55 }
56
57 /**
58 * @param Title $title
59 * @param array $params
60 * @return RefreshLinksJob
61 */
62 public static function newPrioritized( Title $title, array $params ) {
63 $job = new self( $title, $params );
64 $job->command = 'refreshLinksPrioritized';
65
66 return $job;
67 }
68
69 /**
70 * @param Title $title
71 * @param array $params
72 * @return RefreshLinksJob
73 */
74 public static function newDynamic( Title $title, array $params ) {
75 $job = new self( $title, $params );
76 $job->command = 'refreshLinksDynamic';
77
78 return $job;
79 }
80
81 function run() {
82 global $wgUpdateRowsPerJob;
83
84 // Job to update all (or a range of) backlink pages for a page
85 if ( !empty( $this->params['recursive'] ) ) {
86 // When the base job branches, wait for the slaves to catch up to the master.
87 // From then on, we know that any template changes at the time the base job was
88 // enqueued will be reflected in backlink page parses when the leaf jobs run.
89 if ( !isset( $params['range'] ) ) {
90 try {
91 wfGetLBFactory()->waitForReplication( [
92 'wiki' => wfWikiID(),
93 'timeout' => self::LAG_WAIT_TIMEOUT
94 ] );
95 } catch ( DBReplicationWaitError $e ) { // only try so hard
96 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
97 $stats->increment( 'refreshlinks.lag_wait_failed' );
98 }
99 }
100 // Carry over information for de-duplication
101 $extraParams = $this->getRootJobParams();
102 $extraParams['triggeredRecursive'] = true;
103 // Convert this into no more than $wgUpdateRowsPerJob RefreshLinks per-title
104 // jobs and possibly a recursive RefreshLinks job for the rest of the backlinks
105 $jobs = BacklinkJobUtils::partitionBacklinkJob(
106 $this,
107 $wgUpdateRowsPerJob,
108 1, // job-per-title
109 [ 'params' => $extraParams ]
110 );
111 JobQueueGroup::singleton()->push( $jobs );
112 // Job to update link tables for a set of titles
113 } elseif ( isset( $this->params['pages'] ) ) {
114 foreach ( $this->params['pages'] as $pageId => $nsAndKey ) {
115 list( $ns, $dbKey ) = $nsAndKey;
116 $this->runForTitle( Title::makeTitleSafe( $ns, $dbKey ) );
117 }
118 // Job to update link tables for a given title
119 } else {
120 $this->runForTitle( $this->title );
121 }
122
123 return true;
124 }
125
126 /**
127 * @param Title $title
128 * @return bool
129 */
130 protected function runForTitle( Title $title ) {
131 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
132
133 $page = WikiPage::factory( $title );
134 $page->loadPageData( WikiPage::READ_LATEST );
135
136 // Serialize links updates by page ID so they see each others' changes
137 $scopedLock = LinksUpdate::acquirePageLock( wfGetDB( DB_MASTER ), $page->getId(), 'job' );
138 // Get the latest ID *after* acquirePageLock() flushed the transaction.
139 // This is used to detect edits/moves after loadPageData() but before the scope lock.
140 // The works around the chicken/egg problem of determining the scope lock key.
141 $latest = $title->getLatestRevID( Title::GAID_FOR_UPDATE );
142
143 if ( !empty( $this->params['triggeringRevisionId'] ) ) {
144 // Fetch the specified revision; lockAndGetLatest() below detects if the page
145 // was edited since and aborts in order to avoid corrupting the link tables
146 $revision = Revision::newFromId(
147 $this->params['triggeringRevisionId'],
148 Revision::READ_LATEST
149 );
150 } else {
151 // Fetch current revision; READ_LATEST reduces lockAndGetLatest() check failures
152 $revision = Revision::newFromTitle( $title, false, Revision::READ_LATEST );
153 }
154
155 if ( !$revision ) {
156 $stats->increment( 'refreshlinks.rev_not_found' );
157 $this->setLastError( "Revision not found for {$title->getPrefixedDBkey()}" );
158 return false; // just deleted?
159 } elseif ( $revision->getId() != $latest || $revision->getPage() !== $page->getId() ) {
160 // Do not clobber over newer updates with older ones. If all jobs where FIFO and
161 // serialized, it would be OK to update links based on older revisions since it
162 // would eventually get to the latest. Since that is not the case (by design),
163 // only update the link tables to a state matching the current revision's output.
164 $stats->increment( 'refreshlinks.rev_not_current' );
165 $this->setLastError( "Revision {$revision->getId()} is not current" );
166 return false;
167 }
168
169 $content = $revision->getContent( Revision::RAW );
170 if ( !$content ) {
171 // If there is no content, pretend the content is empty
172 $content = $revision->getContentHandler()->makeEmptyContent();
173 }
174
175 $parserOutput = false;
176 $parserOptions = $page->makeParserOptions( 'canonical' );
177 // If page_touched changed after this root job, then it is likely that
178 // any views of the pages already resulted in re-parses which are now in
179 // cache. The cache can be reused to avoid expensive parsing in some cases.
180 if ( isset( $this->params['rootJobTimestamp'] ) ) {
181 $opportunistic = !empty( $this->params['isOpportunistic'] );
182
183 $skewedTimestamp = $this->params['rootJobTimestamp'];
184 if ( $opportunistic ) {
185 // Neither clock skew nor DB snapshot/slave lag matter much for such
186 // updates; focus on reusing the (often recently updated) cache
187 } else {
188 // For transclusion updates, the template changes must be reflected
189 $skewedTimestamp = wfTimestamp( TS_MW,
190 wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
191 );
192 }
193
194 if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
195 // Something already updated the backlinks since this job was made
196 $stats->increment( 'refreshlinks.update_skipped' );
197 return true;
198 }
199
200 if ( $page->getTouched() >= $this->params['rootJobTimestamp'] || $opportunistic ) {
201 // Cache is suspected to be up-to-date. As long as the cache rev ID matches
202 // and it reflects the job's triggering change, then it is usable.
203 $parserOutput = ParserCache::singleton()->getDirty( $page, $parserOptions );
204 if ( !$parserOutput
205 || $parserOutput->getCacheRevisionId() != $revision->getId()
206 || $parserOutput->getCacheTime() < $skewedTimestamp
207 ) {
208 $parserOutput = false; // too stale
209 }
210 }
211 }
212
213 // Fetch the current revision and parse it if necessary...
214 if ( $parserOutput ) {
215 $stats->increment( 'refreshlinks.parser_cached' );
216 } else {
217 $start = microtime( true );
218 // Revision ID must be passed to the parser output to get revision variables correct
219 $parserOutput = $content->getParserOutput(
220 $title, $revision->getId(), $parserOptions, false );
221 $elapsed = microtime( true ) - $start;
222 // If it took a long time to render, then save this back to the cache to avoid
223 // wasted CPU by other apaches or job runners. We don't want to always save to
224 // cache as this can cause high cache I/O and LRU churn when a template changes.
225 if ( $elapsed >= self::PARSE_THRESHOLD_SEC
226 && $page->shouldCheckParserCache( $parserOptions, $revision->getId() )
227 && $parserOutput->isCacheable()
228 ) {
229 $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
230 ParserCache::singleton()->save(
231 $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
232 );
233 }
234 $stats->increment( 'refreshlinks.parser_uncached' );
235 }
236
237 $updates = $content->getSecondaryDataUpdates(
238 $title,
239 null,
240 !empty( $this->params['useRecursiveLinksUpdate'] ),
241 $parserOutput
242 );
243
244 $factory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
245 $ticket = $factory->getEmptyTransactionTicket( __METHOD__ );
246 foreach ( $updates as $key => $update ) {
247 $update->setTransactionTicket( $ticket );
248 // FIXME: This code probably shouldn't be here?
249 // Needed by things like Echo notifications which need
250 // to know which user caused the links update
251 if ( $update instanceof LinksUpdate ) {
252 $update->setRevision( $revision );
253 if ( !empty( $this->params['triggeringUser'] ) ) {
254 $userInfo = $this->params['triggeringUser'];
255 if ( $userInfo['userId'] ) {
256 $user = User::newFromId( $userInfo['userId'] );
257 } else {
258 // Anonymous, use the username
259 $user = User::newFromName( $userInfo['userName'], false );
260 }
261 $update->setTriggeringUser( $user );
262 }
263 }
264 }
265
266 DataUpdate::runUpdates( $updates );
267
268 InfoAction::invalidateCache( $title );
269
270 return true;
271 }
272
273 public function getDeduplicationInfo() {
274 $info = parent::getDeduplicationInfo();
275 if ( is_array( $info['params'] ) ) {
276 // For per-pages jobs, the job title is that of the template that changed
277 // (or similar), so remove that since it ruins duplicate detection
278 if ( isset( $info['pages'] ) ) {
279 unset( $info['namespace'] );
280 unset( $info['title'] );
281 }
282 }
283
284 return $info;
285 }
286
287 public function workItemCount() {
288 return isset( $this->params['pages'] ) ? count( $this->params['pages'] ) : 1;
289 }
290 }