Add triggeringRevisionId to LinksUpdate JobSpec
[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
24 /**
25 * Job to update link tables for pages
26 *
27 * This job comes in a few variants:
28 * - a) Recursive jobs to update links for backlink pages for a given title.
29 * These jobs have (recursive:true,table:<table>) set.
30 * - b) Jobs to update links for a set of pages (the job title is ignored).
31 * These jobs have (pages:(<page ID>:(<namespace>,<title>),...) set.
32 * - c) Jobs to update links for a single page (the job title)
33 * These jobs need no extra fields set.
34 *
35 * @ingroup JobQueue
36 */
37 class RefreshLinksJob extends Job {
38 const PARSE_THRESHOLD_SEC = 1.0;
39
40 const CLOCK_FUDGE = 10;
41
42 function __construct( Title $title, array $params ) {
43 parent::__construct( 'refreshLinks', $title, $params );
44 // Base backlink update jobs and per-title update jobs can be de-duplicated.
45 // If template A changes twice before any jobs run, a clean queue will have:
46 // (A base, A base)
47 // The second job is ignored by the queue on insertion.
48 // Suppose, many pages use template A, and that template itself uses template B.
49 // An edit to both will first create two base jobs. A clean FIFO queue will have:
50 // (A base, B base)
51 // When these jobs run, the queue will have per-title and remnant partition jobs:
52 // (titleX,titleY,titleZ,...,A remnant,titleM,titleN,titleO,...,B remnant)
53 // Some these jobs will be the same, and will automatically be ignored by
54 // the queue upon insertion. Some title jobs will run before the duplicate is
55 // inserted, so the work will still be done twice in those cases. More titles
56 // can be de-duplicated as the remnant jobs continue to be broken down. This
57 // works best when $wgUpdateRowsPerJob, and either the pages have few backlinks
58 // and/or the backlink sets for pages A and B are almost identical.
59 $this->removeDuplicates = !isset( $params['range'] )
60 && ( !isset( $params['pages'] ) || count( $params['pages'] ) == 1 );
61 }
62
63 /**
64 * @param Title $title
65 * @param array $params
66 * @return RefreshLinksJob
67 */
68 public static function newPrioritized( Title $title, array $params ) {
69 $job = new self( $title, $params );
70 $job->command = 'refreshLinksPrioritized';
71
72 return $job;
73 }
74
75 /**
76 * @param Title $title
77 * @param array $params
78 * @return RefreshLinksJob
79 */
80 public static function newDynamic( Title $title, array $params ) {
81 $job = new self( $title, $params );
82 $job->command = 'refreshLinksDynamic';
83
84 return $job;
85 }
86
87 function run() {
88 global $wgUpdateRowsPerJob;
89
90 // Job to update all (or a range of) backlink pages for a page
91 if ( !empty( $this->params['recursive'] ) ) {
92 // Carry over information for de-duplication
93 $extraParams = $this->getRootJobParams();
94 // Avoid slave lag when fetching templates.
95 // When the outermost job is run, we know that the caller that enqueued it must have
96 // committed the relevant changes to the DB by now. At that point, record the master
97 // position and pass it along as the job recursively breaks into smaller range jobs.
98 // Hopefully, when leaf jobs are popped, the slaves will have reached that position.
99 if ( isset( $this->params['masterPos'] ) ) {
100 $extraParams['masterPos'] = $this->params['masterPos'];
101 } elseif ( wfGetLB()->getServerCount() > 1 ) {
102 $extraParams['masterPos'] = wfGetLB()->getMasterPos();
103 } else {
104 $extraParams['masterPos'] = false;
105 }
106 $extraParams['triggeredRecursive'] = true;
107 // Convert this into no more than $wgUpdateRowsPerJob RefreshLinks per-title
108 // jobs and possibly a recursive RefreshLinks job for the rest of the backlinks
109 $jobs = BacklinkJobUtils::partitionBacklinkJob(
110 $this,
111 $wgUpdateRowsPerJob,
112 1, // job-per-title
113 array( 'params' => $extraParams )
114 );
115 JobQueueGroup::singleton()->push( $jobs );
116 // Job to update link tables for a set of titles
117 } elseif ( isset( $this->params['pages'] ) ) {
118 foreach ( $this->params['pages'] as $pageId => $nsAndKey ) {
119 list( $ns, $dbKey ) = $nsAndKey;
120 $this->runForTitle( Title::makeTitleSafe( $ns, $dbKey ) );
121 }
122 // Job to update link tables for a given title
123 } else {
124 $this->runForTitle( $this->title );
125 }
126
127 return true;
128 }
129
130 /**
131 * @param Title $title
132 * @return bool
133 */
134 protected function runForTitle( Title $title ) {
135 // Wait for the DB of the current/next slave DB handle to catch up to the master.
136 // This way, we get the correct page_latest for templates or files that just changed
137 // milliseconds ago, having triggered this job to begin with.
138 if ( isset( $this->params['masterPos'] ) && $this->params['masterPos'] !== false ) {
139 wfGetLB()->waitFor( $this->params['masterPos'] );
140 }
141
142 // Clear out title cache data from prior job transaction snapshots
143 $linkCache = LinkCache::singleton();
144 $linkCache->clear();
145
146 // Fetch the current page and revision...
147 $page = WikiPage::factory( $title );
148 $revision = Revision::newFromTitle( $title, false, Revision::READ_NORMAL );
149 if ( !$revision ) {
150 $this->setLastError( "refreshLinks: Article not found {$title->getPrefixedDBkey()}" );
151 return false; // XXX: what if it was just deleted?
152 }
153
154 $content = $revision->getContent( Revision::RAW );
155 if ( !$content ) {
156 // If there is no content, pretend the content is empty
157 $content = $revision->getContentHandler()->makeEmptyContent();
158 }
159
160 $parserOutput = false;
161 $parserOptions = $page->makeParserOptions( 'canonical' );
162 // If page_touched changed after this root job, then it is likely that
163 // any views of the pages already resulted in re-parses which are now in
164 // cache. The cache can be reused to avoid expensive parsing in some cases.
165 if ( isset( $this->params['rootJobTimestamp'] ) ) {
166 $opportunistic = !empty( $this->params['isOpportunistic'] );
167
168 $skewedTimestamp = $this->params['rootJobTimestamp'];
169 if ( $opportunistic ) {
170 // Neither clock skew nor DB snapshot/slave lag matter much for such
171 // updates; focus on reusing the (often recently updated) cache
172 } else {
173 // For transclusion updates, the template changes must be reflected
174 $skewedTimestamp = wfTimestamp( TS_MW,
175 wfTimestamp( TS_UNIX, $skewedTimestamp ) + self::CLOCK_FUDGE
176 );
177 }
178
179 if ( $page->getLinksTimestamp() > $skewedTimestamp ) {
180 // Something already updated the backlinks since this job was made
181 return true;
182 }
183
184 if ( $page->getTouched() >= $skewedTimestamp || $opportunistic ) {
185 // Something bumped page_touched since this job was made
186 // or the cache is otherwise suspected to be up-to-date
187 $parserOutput = ParserCache::singleton()->getDirty( $page, $parserOptions );
188 if ( $parserOutput && $parserOutput->getCacheTime() < $skewedTimestamp ) {
189 $parserOutput = false; // too stale
190 }
191 }
192 }
193
194 // Fetch the current revision and parse it if necessary...
195 if ( $parserOutput == false ) {
196 $start = microtime( true );
197 // Revision ID must be passed to the parser output to get revision variables correct
198 $parserOutput = $content->getParserOutput(
199 $title, $revision->getId(), $parserOptions, false );
200 $elapsed = microtime( true ) - $start;
201 // If it took a long time to render, then save this back to the cache to avoid
202 // wasted CPU by other apaches or job runners. We don't want to always save to
203 // cache as this can cause high cache I/O and LRU churn when a template changes.
204 if ( $elapsed >= self::PARSE_THRESHOLD_SEC
205 && $page->shouldCheckParserCache( $parserOptions, $revision->getId() )
206 && $parserOutput->isCacheable()
207 ) {
208 $ctime = wfTimestamp( TS_MW, (int)$start ); // cache time
209 ParserCache::singleton()->save(
210 $parserOutput, $page, $parserOptions, $ctime, $revision->getId()
211 );
212 }
213 }
214
215 $updates = $content->getSecondaryDataUpdates(
216 $title, null, !empty( $this->params['useRecursiveLinksUpdate'] ), $parserOutput );
217 foreach ( $updates as $key => $update ) {
218 if ( $update instanceof LinksUpdate ) {
219 if ( isset( $this->params['triggeredRecursive'] ) ) {
220 $update->setTriggeredRecursive();
221 }
222 if ( isset( $this->params['triggeringUser'] ) && $this->params['triggeringUser'] ) {
223 $userInfo = $this->params['triggeringUser'];
224 if ( $userInfo['userId'] ) {
225 $user = User::newFromId( $userInfo['userId'] );
226 } else {
227 // Anonymous, use the username
228 $user = User::newFromName( $userInfo['userName'], false );
229 }
230 $update->setTriggeringUser( $user );
231 }
232 if ( isset( $this->params['triggeringRevisionId'] ) && $this->params['triggeringRevisionId'] ) {
233 $revision = Revision::newFromId( $this->params['triggeringRevisionId'] );
234 if ( $revision === null ) {
235 $revision = Revision::newFromId(
236 $this->params['triggeringRevisionId'],
237 Revision::READ_LATEST
238 );
239 }
240 $update->setRevision( $revision );
241 }
242 }
243 }
244
245 DataUpdate::runUpdates( $updates );
246
247 InfoAction::invalidateCache( $title );
248
249 return true;
250 }
251
252 public function getDeduplicationInfo() {
253 $info = parent::getDeduplicationInfo();
254 if ( is_array( $info['params'] ) ) {
255 // Don't let highly unique "masterPos" values ruin duplicate detection
256 unset( $info['params']['masterPos'] );
257 // For per-pages jobs, the job title is that of the template that changed
258 // (or similar), so remove that since it ruins duplicate detection
259 if ( isset( $info['pages'] ) ) {
260 unset( $info['namespace'] );
261 unset( $info['title'] );
262 }
263 }
264
265 return $info;
266 }
267
268 public function workItemCount() {
269 return isset( $this->params['pages'] ) ? count( $this->params['pages'] ) : 1;
270 }
271 }