Merge "Add any prior block to BlockIpComplete hook"
[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 $page = WikiPage::factory( $title );
132 $page->loadPageData( WikiPage::READ_LATEST );
133 if ( !empty( $this->params['triggeringRevisionId'] ) ) {
134 // Fetch the specified revision; lockAndGetLatest() below detects if the page
135 // was edited since and aborts in order to avoid corrupting the link tables
136 $revision = Revision::newFromId(
137 $this->params['triggeringRevisionId'],
138 Revision::READ_LATEST
139 );
140 } else {
141 // Fetch current revision; READ_LATEST reduces lockAndGetLatest() check failures
142 $revision = Revision::newFromTitle( $title, false, Revision::READ_LATEST );
143 }
144
145 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
146
147 if ( !$revision ) {
148 $stats->increment( 'refreshlinks.rev_not_found' );
149 $this->setLastError( "Revision not found for {$title->getPrefixedDBkey()}" );
150 return false; // just deleted?
151 } elseif ( !$revision->isCurrent() || $revision->getPage() != $page->getId() ) {
152 // If the revision isn't current, there's no point in doing a bunch
153 // of work just to fail at the lockAndGetLatest() check later.
154 $stats->increment( 'refreshlinks.rev_not_current' );
155 $this->setLastError( "Revision {$revision->getId()} is not current" );
156 return false;
157 }
158
159 $content = $revision->getContent( Revision::RAW );
160 if ( !$content ) {
161 // If there is no content, pretend the content is empty
162 $content = $revision->getContentHandler()->makeEmptyContent();
163 }
164
165 $parserOutput = false;
166 $parserOptions = $page->makeParserOptions( 'canonical' );
167 // If page_touched changed after this root job, then it is likely that
168 // any views of the pages already resulted in re-parses which are now in
169 // cache. The cache can be reused to avoid expensive parsing in some cases.
170 if ( isset( $this->params['rootJobTimestamp'] ) ) {
171 $opportunistic = !empty( $this->params['isOpportunistic'] );
172
173 $skewedTimestamp = $this->params['rootJobTimestamp'];
174 if ( $opportunistic ) {
175 // Neither clock skew nor DB snapshot/slave lag matter much for such
176 // updates; focus on reusing the (often recently updated) cache
177 } else {
178 // For transclusion updates, the template changes must be reflected
179 $skewedTimestamp = wfTimestamp( TS_MW,
180 wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
181 );
182 }
183
184 if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
185 // Something already updated the backlinks since this job was made
186 $stats->increment( 'refreshlinks.update_skipped' );
187 return true;
188 }
189
190 if ( $page->getTouched() >= $this->params['rootJobTimestamp'] || $opportunistic ) {
191 // Cache is suspected to be up-to-date. As long as the cache rev ID matches
192 // and it reflects the job's triggering change, then it is usable.
193 $parserOutput = ParserCache::singleton()->getDirty( $page, $parserOptions );
194 if ( !$parserOutput
195 || $parserOutput->getCacheRevisionId() != $revision->getId()
196 || $parserOutput->getCacheTime() < $skewedTimestamp
197 ) {
198 $parserOutput = false; // too stale
199 }
200 }
201 }
202
203 // Fetch the current revision and parse it if necessary...
204 if ( $parserOutput ) {
205 $stats->increment( 'refreshlinks.parser_cached' );
206 } else {
207 $start = microtime( true );
208 // Revision ID must be passed to the parser output to get revision variables correct
209 $parserOutput = $content->getParserOutput(
210 $title, $revision->getId(), $parserOptions, false );
211 $elapsed = microtime( true ) - $start;
212 // If it took a long time to render, then save this back to the cache to avoid
213 // wasted CPU by other apaches or job runners. We don't want to always save to
214 // cache as this can cause high cache I/O and LRU churn when a template changes.
215 if ( $elapsed >= self::PARSE_THRESHOLD_SEC
216 && $page->shouldCheckParserCache( $parserOptions, $revision->getId() )
217 && $parserOutput->isCacheable()
218 ) {
219 $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
220 ParserCache::singleton()->save(
221 $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
222 );
223 }
224 $stats->increment( 'refreshlinks.parser_uncached' );
225 }
226
227 $updates = $content->getSecondaryDataUpdates(
228 $title,
229 null,
230 !empty( $this->params['useRecursiveLinksUpdate'] ),
231 $parserOutput
232 );
233
234 foreach ( $updates as $key => $update ) {
235 // FIXME: This code probably shouldn't be here?
236 // Needed by things like Echo notifications which need
237 // to know which user caused the links update
238 if ( $update instanceof LinksUpdate ) {
239 $update->setRevision( $revision );
240 if ( !empty( $this->params['triggeringUser'] ) ) {
241 $userInfo = $this->params['triggeringUser'];
242 if ( $userInfo['userId'] ) {
243 $user = User::newFromId( $userInfo['userId'] );
244 } else {
245 // Anonymous, use the username
246 $user = User::newFromName( $userInfo['userName'], false );
247 }
248 $update->setTriggeringUser( $user );
249 }
250 }
251 }
252
253 $latestNow = $page->lockAndGetLatest();
254 if ( !$latestNow || $revision->getId() != $latestNow ) {
255 // Do not clobber over newer updates with older ones. If all jobs where FIFO and
256 // serialized, it would be OK to update links based on older revisions since it
257 // would eventually get to the latest. Since that is not the case (by design),
258 // only update the link tables to a state matching the current revision's output.
259 $stats->increment( 'refreshlinks.rev_cas_failure' );
260 $this->setLastError( "page_latest changed from {$revision->getId()} to $latestNow" );
261 return false;
262 }
263
264 DataUpdate::runUpdates( $updates );
265
266 InfoAction::invalidateCache( $title );
267
268 return true;
269 }
270
271 public function getDeduplicationInfo() {
272 $info = parent::getDeduplicationInfo();
273 if ( is_array( $info['params'] ) ) {
274 // For per-pages jobs, the job title is that of the template that changed
275 // (or similar), so remove that since it ruins duplicate detection
276 if ( isset( $info['pages'] ) ) {
277 unset( $info['namespace'] );
278 unset( $info['title'] );
279 }
280 }
281
282 return $info;
283 }
284
285 public function workItemCount() {
286 return isset( $this->params['pages'] ) ? count( $this->params['pages'] ) : 1;
287 }
288 }