Merge "RecentChanges updated to use pseudo elements for presentation"
[lhc/web/wiklou.git] / includes / jobqueue / Job.php
1 <?php
2 /**
3 * Job queue task base code.
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 * @defgroup JobQueue JobQueue
22 */
23
24 /**
25 * Class to both describe a background job and handle jobs.
26 * To push jobs onto queues, use JobQueueGroup::singleton()->push();
27 *
28 * @ingroup JobQueue
29 */
30 abstract class Job implements IJobSpecification {
31 /** @var string */
32 public $command;
33
34 /** @var array Array of job parameters */
35 public $params;
36
37 /** @var array Additional queue metadata */
38 public $metadata = [];
39
40 /** @var Title */
41 protected $title;
42
43 /** @var bool Expensive jobs may set this to true */
44 protected $removeDuplicates = false;
45
46 /** @var string Text for error that occurred last */
47 protected $error;
48
49 /** @var callable[] */
50 protected $teardownCallbacks = [];
51
52 /** @var int Bitfield of JOB_* class constants */
53 protected $executionFlags = 0;
54
55 /** @var int Job must not be wrapped in the usual explicit LBFactory transaction round */
56 const JOB_NO_EXPLICIT_TRX_ROUND = 1;
57
58 /**
59 * Run the job
60 * @return bool Success
61 */
62 abstract public function run();
63
64 /**
65 * Create the appropriate object to handle a specific job
66 *
67 * @param string $command Job command
68 * @param array $params Job parameters
69 * @throws InvalidArgumentException
70 * @return Job
71 */
72 public static function factory( $command, $params = [] ) {
73 global $wgJobClasses;
74
75 if ( $params instanceof Title ) {
76 // Backwards compatibility for old signature ($command, $title, $params)
77 $title = $params;
78 $params = func_num_args() >= 3 ? func_get_arg( 2 ) : [];
79 } else {
80 // Subclasses can override getTitle() to return something more meaningful
81 $title = Title::makeTitle( NS_SPECIAL, 'Blankpage' );
82 }
83
84 if ( isset( $wgJobClasses[$command] ) ) {
85 $handler = $wgJobClasses[$command];
86
87 if ( is_callable( $handler ) ) {
88 $job = call_user_func( $handler, $title, $params );
89 } elseif ( class_exists( $handler ) ) {
90 $job = new $handler( $title, $params );
91 } else {
92 $job = null;
93 }
94
95 if ( $job instanceof Job ) {
96 $job->command = $command;
97
98 return $job;
99 } else {
100 throw new InvalidArgumentException( "Could instantiate job '$command': bad spec!" );
101 }
102 }
103
104 throw new InvalidArgumentException( "Invalid job command '{$command}'" );
105 }
106
107 /**
108 * @param string $command
109 * @param array $params
110 */
111 public function __construct( $command, $params = [] ) {
112 if ( $params instanceof Title ) {
113 // Backwards compatibility for old signature ($command, $title, $params)
114 $title = $params;
115 $params = func_num_args() >= 3 ? func_get_arg( 2 ) : [];
116 } else {
117 // Subclasses can override getTitle() to return something more meaningful
118 $title = Title::makeTitle( NS_SPECIAL, 'Blankpage' );
119 }
120
121 $this->command = $command;
122 $this->title = $title;
123 $this->params = is_array( $params ) ? $params : []; // sanity
124 if ( !isset( $this->params['requestId'] ) ) {
125 $this->params['requestId'] = WebRequest::getRequestId();
126 }
127 }
128
129 /**
130 * @param int $flag JOB_* class constant
131 * @return bool
132 * @since 1.31
133 */
134 public function hasExecutionFlag( $flag ) {
135 return ( $this->executionFlags & $flag ) === $flag;
136 }
137
138 /**
139 * @return string
140 */
141 public function getType() {
142 return $this->command;
143 }
144
145 /**
146 * @return Title
147 */
148 public function getTitle() {
149 return $this->title;
150 }
151
152 /**
153 * @return array
154 */
155 public function getParams() {
156 return $this->params;
157 }
158
159 /**
160 * @return int|null UNIX timestamp to delay running this job until, otherwise null
161 * @since 1.22
162 */
163 public function getReleaseTimestamp() {
164 return isset( $this->params['jobReleaseTimestamp'] )
165 ? wfTimestampOrNull( TS_UNIX, $this->params['jobReleaseTimestamp'] )
166 : null;
167 }
168
169 /**
170 * @return int|null UNIX timestamp of when the job was queued, or null
171 * @since 1.26
172 */
173 public function getQueuedTimestamp() {
174 return isset( $this->metadata['timestamp'] )
175 ? wfTimestampOrNull( TS_UNIX, $this->metadata['timestamp'] )
176 : null;
177 }
178
179 /**
180 * @return string|null Id of the request that created this job. Follows
181 * jobs recursively, allowing to track the id of the request that started a
182 * job when jobs insert jobs which insert other jobs.
183 * @since 1.27
184 */
185 public function getRequestId() {
186 return $this->params['requestId'] ?? null;
187 }
188
189 /**
190 * @return int|null UNIX timestamp of when the job was runnable, or null
191 * @since 1.26
192 */
193 public function getReadyTimestamp() {
194 return $this->getReleaseTimestamp() ?: $this->getQueuedTimestamp();
195 }
196
197 /**
198 * Whether the queue should reject insertion of this job if a duplicate exists
199 *
200 * This can be used to avoid duplicated effort or combined with delayed jobs to
201 * coalesce updates into larger batches. Claimed jobs are never treated as
202 * duplicates of new jobs, and some queues may allow a few duplicates due to
203 * network partitions and fail-over. Thus, additional locking is needed to
204 * enforce mutual exclusion if this is really needed.
205 *
206 * @return bool
207 */
208 public function ignoreDuplicates() {
209 return $this->removeDuplicates;
210 }
211
212 /**
213 * @return bool Whether this job can be retried on failure by job runners
214 * @since 1.21
215 */
216 public function allowRetries() {
217 return true;
218 }
219
220 /**
221 * @return int Number of actually "work items" handled in this job
222 * @see $wgJobBackoffThrottling
223 * @since 1.23
224 */
225 public function workItemCount() {
226 return 1;
227 }
228
229 /**
230 * Subclasses may need to override this to make duplication detection work.
231 * The resulting map conveys everything that makes the job unique. This is
232 * only checked if ignoreDuplicates() returns true, meaning that duplicate
233 * jobs are supposed to be ignored.
234 *
235 * @return array Map of key/values
236 * @since 1.21
237 */
238 public function getDeduplicationInfo() {
239 $info = [
240 'type' => $this->getType(),
241 'namespace' => $this->getTitle()->getNamespace(),
242 'title' => $this->getTitle()->getDBkey(),
243 'params' => $this->getParams()
244 ];
245 if ( is_array( $info['params'] ) ) {
246 // Identical jobs with different "root" jobs should count as duplicates
247 unset( $info['params']['rootJobSignature'] );
248 unset( $info['params']['rootJobTimestamp'] );
249 // Likewise for jobs with different delay times
250 unset( $info['params']['jobReleaseTimestamp'] );
251 // Identical jobs from different requests should count as duplicates
252 unset( $info['params']['requestId'] );
253 // Queues pack and hash this array, so normalize the order
254 ksort( $info['params'] );
255 }
256
257 return $info;
258 }
259
260 /**
261 * Get "root job" parameters for a task
262 *
263 * This is used to no-op redundant jobs, including child jobs of jobs,
264 * as long as the children inherit the root job parameters. When a job
265 * with root job parameters and "rootJobIsSelf" set is pushed, the
266 * deduplicateRootJob() method is automatically called on it. If the
267 * root job is only virtual and not actually pushed (e.g. the sub-jobs
268 * are inserted directly), then call deduplicateRootJob() directly.
269 *
270 * @see JobQueue::deduplicateRootJob()
271 *
272 * @param string $key A key that identifies the task
273 * @return array Map of:
274 * - rootJobIsSelf : true
275 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
276 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
277 * @since 1.21
278 */
279 public static function newRootJobParams( $key ) {
280 return [
281 'rootJobIsSelf' => true,
282 'rootJobSignature' => sha1( $key ),
283 'rootJobTimestamp' => wfTimestampNow()
284 ];
285 }
286
287 /**
288 * @see JobQueue::deduplicateRootJob()
289 * @return array
290 * @since 1.21
291 */
292 public function getRootJobParams() {
293 return [
294 'rootJobSignature' => $this->params['rootJobSignature'] ?? null,
295 'rootJobTimestamp' => $this->params['rootJobTimestamp'] ?? null
296 ];
297 }
298
299 /**
300 * @see JobQueue::deduplicateRootJob()
301 * @return bool
302 * @since 1.22
303 */
304 public function hasRootJobParams() {
305 return isset( $this->params['rootJobSignature'] )
306 && isset( $this->params['rootJobTimestamp'] );
307 }
308
309 /**
310 * @see JobQueue::deduplicateRootJob()
311 * @return bool Whether this is job is a root job
312 */
313 public function isRootJob() {
314 return $this->hasRootJobParams() && !empty( $this->params['rootJobIsSelf'] );
315 }
316
317 /**
318 * @param callable $callback A function with one parameter, the success status, which will be
319 * false if the job failed or it succeeded but the DB changes could not be committed or
320 * any deferred updates threw an exception. (This parameter was added in 1.28.)
321 * @since 1.27
322 */
323 protected function addTeardownCallback( $callback ) {
324 $this->teardownCallbacks[] = $callback;
325 }
326
327 /**
328 * Do any final cleanup after run(), deferred updates, and all DB commits happen
329 * @param bool $status Whether the job, its deferred updates, and DB commit all succeeded
330 * @since 1.27
331 */
332 public function teardown( $status ) {
333 foreach ( $this->teardownCallbacks as $callback ) {
334 call_user_func( $callback, $status );
335 }
336 }
337
338 /**
339 * @return string
340 */
341 public function toString() {
342 $paramString = '';
343 if ( $this->params ) {
344 foreach ( $this->params as $key => $value ) {
345 if ( $paramString != '' ) {
346 $paramString .= ' ';
347 }
348 if ( is_array( $value ) ) {
349 $filteredValue = [];
350 foreach ( $value as $k => $v ) {
351 $json = FormatJson::encode( $v );
352 if ( $json === false || mb_strlen( $json ) > 512 ) {
353 $filteredValue[$k] = gettype( $v ) . '(...)';
354 } else {
355 $filteredValue[$k] = $v;
356 }
357 }
358 if ( count( $filteredValue ) <= 10 ) {
359 $value = FormatJson::encode( $filteredValue );
360 } else {
361 $value = "array(" . count( $value ) . ")";
362 }
363 } elseif ( is_object( $value ) && !method_exists( $value, '__toString' ) ) {
364 $value = "object(" . get_class( $value ) . ")";
365 }
366
367 $flatValue = (string)$value;
368 if ( mb_strlen( $value ) > 1024 ) {
369 $flatValue = "string(" . mb_strlen( $value ) . ")";
370 }
371
372 $paramString .= "$key={$flatValue}";
373 }
374 }
375
376 $metaString = '';
377 foreach ( $this->metadata as $key => $value ) {
378 if ( is_scalar( $value ) && mb_strlen( $value ) < 1024 ) {
379 $metaString .= ( $metaString ? ",$key=$value" : "$key=$value" );
380 }
381 }
382
383 $s = $this->command;
384 if ( is_object( $this->title ) ) {
385 $s .= " {$this->title->getPrefixedDBkey()}";
386 }
387 if ( $paramString != '' ) {
388 $s .= " $paramString";
389 }
390 if ( $metaString != '' ) {
391 $s .= " ($metaString)";
392 }
393
394 return $s;
395 }
396
397 protected function setLastError( $error ) {
398 $this->error = $error;
399 }
400
401 public function getLastError() {
402 return $this->error;
403 }
404 }