MediaWiki master
Job.php
Go to the documentation of this file.
1<?php
25
40abstract class Job implements RunnableJob {
42 public $command;
43
45 public $params;
46
48 public $metadata = [];
49
51 protected $title;
52
54 protected $removeDuplicates = false;
55
57 protected $error;
58
60 protected $teardownCallbacks = [];
61
63 protected $executionFlags = 0;
64
75 public static function factory( $command, $params = [] ) {
76 $factory = MediaWikiServices::getInstance()->getJobFactory();
77
78 // FIXME: fix handling for legacy signature!
79 // @phan-suppress-next-line PhanParamTooFewUnpack one argument is known to be present.
80 return $factory->newJob( ...func_get_args() );
81 }
82
89 public function __construct( $command, $params = null ) {
90 if ( $params instanceof PageReference ) {
91 // Backwards compatibility for old signature ($command, $title, $params)
92 $page = $params;
93 $params = func_num_args() >= 3 ? func_get_arg( 2 ) : [];
94 } else {
95 // Newer jobs may choose to not have a top-level title (e.g. GenericParameterJob)
96 $page = null;
97 }
98
99 if ( !is_array( $params ) ) {
100 throw new InvalidArgumentException( '$params must be an array' );
101 }
102
103 if (
104 $page &&
105 !isset( $params['namespace'] ) &&
106 !isset( $params['title'] )
107 ) {
108 // When constructing this class for submitting to the queue,
109 // normalise the $page arg of old job classes as part of $params.
110 $params['namespace'] = $page->getNamespace();
111 $params['title'] = $page->getDBkey();
112 }
113
114 $this->command = $command;
115 $this->params = $params + [
116 'requestId' => Telemetry::getInstance()->getRequestId(),
117 ];
118
119 if ( $this->title === null ) {
120 // Set this field for access via getTitle().
121 $this->title = ( isset( $params['namespace'] ) && isset( $params['title'] ) )
122 ? Title::makeTitle( $params['namespace'], $params['title'] )
123 // GenericParameterJob classes without namespace/title params
124 // should not use getTitle(). Set an invalid title as placeholder.
125 : Title::makeTitle( NS_SPECIAL, '' );
126 }
127 }
128
133 public function hasExecutionFlag( $flag ) {
134 return ( $this->executionFlags & $flag ) === $flag;
135 }
136
141 public function getType() {
142 return $this->command;
143 }
144
148 final public function getTitle() {
149 return $this->title;
150 }
151
156 public function getParams() {
157 return $this->params;
158 }
159
166 public function getMetadata( $field = null ) {
167 if ( $field === null ) {
168 return $this->metadata;
169 }
170
171 return $this->metadata[$field] ?? null;
172 }
173
181 public function setMetadata( $field, $value ) {
182 $old = $this->getMetadata( $field );
183 if ( $value === null ) {
184 unset( $this->metadata[$field] );
185 } else {
186 $this->metadata[$field] = $value;
187 }
188
189 return $old;
190 }
191
197 public function getReleaseTimestamp() {
198 $time = wfTimestampOrNull( TS_UNIX, $this->params['jobReleaseTimestamp'] ?? null );
199 return $time ? (int)$time : null;
200 }
201
206 public function getQueuedTimestamp() {
207 $time = wfTimestampOrNull( TS_UNIX, $this->metadata['timestamp'] ?? null );
208 return $time ? (int)$time : null;
209 }
210
215 public function getRequestId() {
216 return $this->params['requestId'] ?? null;
217 }
218
223 public function getReadyTimestamp() {
224 return $this->getReleaseTimestamp() ?: $this->getQueuedTimestamp();
225 }
226
240 public function ignoreDuplicates() {
241 return $this->removeDuplicates;
242 }
243
248 public function allowRetries() {
249 return true;
250 }
251
256 public function workItemCount() {
257 return 1;
258 }
259
270 public function getDeduplicationInfo() {
271 $info = [
272 'type' => $this->getType(),
273 'params' => $this->getParams()
274 ];
275 if ( is_array( $info['params'] ) ) {
276 // Identical jobs with different "root" jobs should count as duplicates
277 unset( $info['params']['rootJobSignature'] );
278 unset( $info['params']['rootJobTimestamp'] );
279 // Likewise for jobs with different delay times
280 unset( $info['params']['jobReleaseTimestamp'] );
281 // Identical jobs from different requests should count as duplicates
282 unset( $info['params']['requestId'] );
283 // Queues pack and hash this array, so normalize the order
284 ksort( $info['params'] );
285 }
286
287 return $info;
288 }
289
309 public static function newRootJobParams( $key ) {
310 return [
311 'rootJobIsSelf' => true,
312 'rootJobSignature' => sha1( $key ),
313 'rootJobTimestamp' => wfTimestampNow()
314 ];
315 }
316
323 public function getRootJobParams() {
324 return [
325 'rootJobSignature' => $this->params['rootJobSignature'] ?? null,
326 'rootJobTimestamp' => $this->params['rootJobTimestamp'] ?? null
327 ];
328 }
329
336 public function hasRootJobParams() {
337 return isset( $this->params['rootJobSignature'] )
338 && isset( $this->params['rootJobTimestamp'] );
339 }
340
346 public function isRootJob() {
347 return $this->hasRootJobParams() && !empty( $this->params['rootJobIsSelf'] );
348 }
349
356 protected function addTeardownCallback( $callback ) {
357 $this->teardownCallbacks[] = $callback;
358 }
359
364 public function teardown( $status ) {
365 foreach ( $this->teardownCallbacks as $callback ) {
366 call_user_func( $callback, $status );
367 }
368 }
369
374 public function toString() {
375 $paramString = '';
376 if ( $this->params ) {
377 foreach ( $this->params as $key => $value ) {
378 if ( $paramString != '' ) {
379 $paramString .= ' ';
380 }
381 if ( is_array( $value ) ) {
382 $filteredValue = [];
383 foreach ( $value as $k => $v ) {
384 $json = FormatJson::encode( $v );
385 if ( $json === false || mb_strlen( $json ) > 512 ) {
386 $filteredValue[$k] = gettype( $v ) . '(...)';
387 } else {
388 $filteredValue[$k] = $v;
389 }
390 }
391 if ( count( $filteredValue ) <= 10 ) {
392 $value = FormatJson::encode( $filteredValue );
393 } else {
394 $value = "array(" . count( $value ) . ")";
395 }
396 } elseif ( is_object( $value ) && !method_exists( $value, '__toString' ) ) {
397 $value = "object(" . get_class( $value ) . ")";
398 }
399
400 $flatValue = (string)$value;
401 if ( mb_strlen( $flatValue ) > 1024 ) {
402 $flatValue = "string(" . mb_strlen( $value ) . ")";
403 }
404
405 // Remove newline characters from the value, since
406 // newlines indicate new job lines in log files
407 $flatValue = preg_replace( '/\s+/', ' ', $flatValue );
408
409 $paramString .= "$key={$flatValue}";
410 }
411 }
412
413 $metaString = '';
414 foreach ( $this->metadata as $key => $value ) {
415 if ( is_scalar( $value ) && mb_strlen( $value ) < 1024 ) {
416 $metaString .= ( $metaString ? ",$key=$value" : "$key=$value" );
417 }
418 }
419
420 $s = $this->command;
421 if ( is_object( $this->title ) ) {
422 $s .= ' ' . $this->title->getPrefixedDBkey();
423 }
424 if ( $paramString != '' ) {
425 $s .= " $paramString";
426 }
427 if ( $metaString != '' ) {
428 $s .= " ($metaString)";
429 }
430
431 return $s;
432 }
433
434 protected function setLastError( $error ) {
435 $this->error = $error;
436 }
437
442 public function getLastError() {
443 return $this->error;
444 }
445}
const NS_SPECIAL
Definition Defines.php:53
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
array $params
The job parameters.
Describe and execute a background job.
Definition Job.php:40
hasRootJobParams()
Definition Job.php:336
string $command
Definition Job.php:42
setMetadata( $field, $value)
Definition Job.php:181
getParams()
array Parameters that specify sources, targets, and options for execution
Definition Job.php:156
getReadyTimestamp()
int|null UNIX timestamp of when the job was runnable, or null 1.26
Definition Job.php:223
toString()
string Debugging string describing the job
Definition Job.php:374
getType()
string Job type that defines what sort of changes this job makes
Definition Job.php:141
Title $title
Definition Job.php:51
getRootJobParams()
Definition Job.php:323
hasExecutionFlag( $flag)
bool 1.31
Definition Job.php:133
callable[] $teardownCallbacks
Definition Job.php:60
getQueuedTimestamp()
Definition Job.php:206
bool $removeDuplicates
Expensive jobs may set this to true.
Definition Job.php:54
setLastError( $error)
Definition Job.php:434
getMetadata( $field=null)
Definition Job.php:166
teardown( $status)
Definition Job.php:364
isRootJob()
Definition Job.php:346
addTeardownCallback( $callback)
Definition Job.php:356
array $params
Array of job parameters.
Definition Job.php:45
getTitle()
Definition Job.php:148
array $metadata
Additional queue metadata.
Definition Job.php:48
static factory( $command, $params=[])
Create the appropriate object to handle a specific job.
Definition Job.php:75
int $executionFlags
Bitfield of JOB_* class constants.
Definition Job.php:63
workItemCount()
Definition Job.php:256
getRequestId()
string|null Id of the request that created this job. Follows jobs recursively, allowing to track the ...
Definition Job.php:215
static newRootJobParams( $key)
Get "root job" parameters for a task.
Definition Job.php:309
getDeduplicationInfo()
Subclasses may need to override this to make duplication detection work.
Definition Job.php:270
getReleaseTimestamp()
Definition Job.php:197
ignoreDuplicates()
Whether the queue should reject insertion of this job if a duplicate exists.
Definition Job.php:240
getLastError()
string
Definition Job.php:442
string $error
Text for error that occurred last.
Definition Job.php:57
allowRetries()
In some setups (i.e. when using change-propagation) jobs may still be retried even when this is false...
Definition Job.php:248
__construct( $command, $params=null)
Definition Job.php:89
Service for handling telemetry data.
Definition Telemetry.php:29
Service locator for MediaWiki core services.
Represents a title within MediaWiki.
Definition Title.php:78
Interface for objects (potentially) representing a page that can be viewable and linked to on a wiki.
Job that has a run() method and metadata accessors for JobQueue::pop() and JobQueue::ack().