3 * Job queue task base code.
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.
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.
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
21 * @defgroup JobQueue JobQueue
25 * Class to both describe a background job and handle jobs.
26 * The queue aspects of this class are now deprecated.
27 * Using the class to push jobs onto queues is deprecated (use JobSpecification).
31 abstract class Job
implements IJobSpecification
{
35 /** @var array Array of job parameters */
38 /** @var array Additional queue metadata */
39 public $metadata = [];
44 /** @var bool Expensive jobs may set this to true */
45 protected $removeDuplicates;
47 /** @var string Text for error that occurred last */
50 /** @var callable[] */
51 protected $teardownCallbacks = [];
55 * @return bool Success
57 abstract public function run();
60 * Create the appropriate object to handle a specific job
62 * @param string $command Job command
63 * @param Title $title Associated title
64 * @param array $params Job parameters
68 public static function factory( $command, Title
$title, $params = [] ) {
71 if ( isset( $wgJobClasses[$command] ) ) {
72 $handler = $wgJobClasses[$command];
74 if ( is_callable( $handler ) ) {
75 $job = call_user_func( $handler, $title, $params );
76 } elseif ( class_exists( $handler ) ) {
77 $job = new $handler( $title, $params );
82 if ( $job instanceof Job
) {
83 $job->command
= $command;
86 throw new InvalidArgumentException( "Cannot instantiate job '$command': bad spec!" );
90 throw new InvalidArgumentException( "Invalid job command '{$command}'" );
94 * @param string $command
96 * @param array|bool $params Can not be === true
98 public function __construct( $command, $title, $params = false ) {
99 $this->command
= $command;
100 $this->title
= $title;
101 $this->params
= is_array( $params ) ?
$params : []; // sanity
103 // expensive jobs may set this to true
104 $this->removeDuplicates
= false;
106 if ( !isset( $this->params
['requestId'] ) ) {
107 $this->params
['requestId'] = WebRequest
::getRequestId();
112 * Batch-insert a group of jobs into the queue.
113 * This will be wrapped in a transaction with a forced commit.
115 * This may add duplicate at insert time, but they will be
116 * removed later on, when the first one is popped.
118 * @param Job[] $jobs Array of Job objects
120 * @deprecated since 1.21
122 public static function batchInsert( $jobs ) {
123 wfDeprecated( __METHOD__
, '1.21' );
124 JobQueueGroup
::singleton()->push( $jobs );
131 public function getType() {
132 return $this->command
;
138 public function getTitle() {
145 public function getParams() {
146 return $this->params
;
150 * @return int|null UNIX timestamp to delay running this job until, otherwise null
153 public function getReleaseTimestamp() {
154 return isset( $this->params
['jobReleaseTimestamp'] )
155 ?
wfTimestampOrNull( TS_UNIX
, $this->params
['jobReleaseTimestamp'] )
160 * @return int|null UNIX timestamp of when the job was queued, or null
163 public function getQueuedTimestamp() {
164 return isset( $this->metadata
['timestamp'] )
165 ?
wfTimestampOrNull( TS_UNIX
, $this->metadata
['timestamp'] )
170 * @return string|null Id of the request that created this job. Follows
171 * jobs recursively, allowing to track the id of the request that started a
172 * job when jobs insert jobs which insert other jobs.
175 public function getRequestId() {
176 return isset( $this->params
['requestId'] )
177 ?
$this->params
['requestId']
182 * @return int|null UNIX timestamp of when the job was runnable, or null
185 public function getReadyTimestamp() {
186 return $this->getReleaseTimestamp() ?
: $this->getQueuedTimestamp();
190 * Whether the queue should reject insertion of this job if a duplicate exists
192 * This can be used to avoid duplicated effort or combined with delayed jobs to
193 * coalesce updates into larger batches. Claimed jobs are never treated as
194 * duplicates of new jobs, and some queues may allow a few duplicates due to
195 * network partitions and fail-over. Thus, additional locking is needed to
196 * enforce mutual exclusion if this is really needed.
200 public function ignoreDuplicates() {
201 return $this->removeDuplicates
;
205 * @return bool Whether this job can be retried on failure by job runners
208 public function allowRetries() {
213 * @return int Number of actually "work items" handled in this job
214 * @see $wgJobBackoffThrottling
217 public function workItemCount() {
222 * Subclasses may need to override this to make duplication detection work.
223 * The resulting map conveys everything that makes the job unique. This is
224 * only checked if ignoreDuplicates() returns true, meaning that duplicate
225 * jobs are supposed to be ignored.
227 * @return array Map of key/values
230 public function getDeduplicationInfo() {
232 'type' => $this->getType(),
233 'namespace' => $this->getTitle()->getNamespace(),
234 'title' => $this->getTitle()->getDBkey(),
235 'params' => $this->getParams()
237 if ( is_array( $info['params'] ) ) {
238 // Identical jobs with different "root" jobs should count as duplicates
239 unset( $info['params']['rootJobSignature'] );
240 unset( $info['params']['rootJobTimestamp'] );
241 // Likewise for jobs with different delay times
242 unset( $info['params']['jobReleaseTimestamp'] );
243 // Identical jobs from different requests should count as duplicates
244 unset( $info['params']['requestId'] );
245 // Queues pack and hash this array, so normalize the order
246 ksort( $info['params'] );
253 * Get "root job" parameters for a task
255 * This is used to no-op redundant jobs, including child jobs of jobs,
256 * as long as the children inherit the root job parameters. When a job
257 * with root job parameters and "rootJobIsSelf" set is pushed, the
258 * deduplicateRootJob() method is automatically called on it. If the
259 * root job is only virtual and not actually pushed (e.g. the sub-jobs
260 * are inserted directly), then call deduplicateRootJob() directly.
262 * @see JobQueue::deduplicateRootJob()
264 * @param string $key A key that identifies the task
265 * @return array Map of:
266 * - rootJobIsSelf : true
267 * - rootJobSignature : hash (e.g. SHA1) that identifies the task
268 * - rootJobTimestamp : TS_MW timestamp of this instance of the task
271 public static function newRootJobParams( $key ) {
273 'rootJobIsSelf' => true,
274 'rootJobSignature' => sha1( $key ),
275 'rootJobTimestamp' => wfTimestampNow()
280 * @see JobQueue::deduplicateRootJob()
284 public function getRootJobParams() {
286 'rootJobSignature' => isset( $this->params
['rootJobSignature'] )
287 ?
$this->params
['rootJobSignature']
289 'rootJobTimestamp' => isset( $this->params
['rootJobTimestamp'] )
290 ?
$this->params
['rootJobTimestamp']
296 * @see JobQueue::deduplicateRootJob()
300 public function hasRootJobParams() {
301 return isset( $this->params
['rootJobSignature'] )
302 && isset( $this->params
['rootJobTimestamp'] );
306 * @see JobQueue::deduplicateRootJob()
307 * @return bool Whether this is job is a root job
309 public function isRootJob() {
310 return $this->hasRootJobParams() && !empty( $this->params
['rootJobIsSelf'] );
314 * @param callable $callback A function with one parameter, the success status, which will be
315 * false if the job failed or it succeeded but the DB changes could not be committed or
316 * any deferred updates threw an exception. (This parameter was added in 1.28.)
319 protected function addTeardownCallback( $callback ) {
320 $this->teardownCallbacks
[] = $callback;
324 * Do any final cleanup after run(), deferred updates, and all DB commits happen
325 * @param bool $status Whether the job, its deferred updates, and DB commit all succeeded
328 public function teardown( $status ) {
329 foreach ( $this->teardownCallbacks
as $callback ) {
330 call_user_func( $callback, $status );
335 * Insert a single job into the queue.
336 * @return bool True on success
337 * @deprecated since 1.21
339 public function insert() {
340 JobQueueGroup
::singleton()->push( $this );
347 public function toString() {
349 if ( $this->params
) {
350 foreach ( $this->params
as $key => $value ) {
351 if ( $paramString != '' ) {
354 if ( is_array( $value ) ) {
356 foreach ( $value as $k => $v ) {
357 $json = FormatJson
::encode( $v );
358 if ( $json === false ||
mb_strlen( $json ) > 512 ) {
359 $filteredValue[$k] = gettype( $v ) . '(...)';
361 $filteredValue[$k] = $v;
364 if ( count( $filteredValue ) <= 10 ) {
365 $value = FormatJson
::encode( $filteredValue );
367 $value = "array(" . count( $value ) . ")";
369 } elseif ( is_object( $value ) && !method_exists( $value, '__toString' ) ) {
370 $value = "object(" . get_class( $value ) . ")";
373 $flatValue = (string)$value;
374 if ( mb_strlen( $value ) > 1024 ) {
375 $flatValue = "string(" . mb_strlen( $value ) . ")";
378 $paramString .= "$key={$flatValue}";
383 foreach ( $this->metadata
as $key => $value ) {
384 if ( is_scalar( $value ) && mb_strlen( $value ) < 1024 ) {
385 $metaString .= ( $metaString ?
",$key=$value" : "$key=$value" );
390 if ( is_object( $this->title
) ) {
391 $s .= " {$this->title->getPrefixedDBkey()}";
393 if ( $paramString != '' ) {
394 $s .= " $paramString";
396 if ( $metaString != '' ) {
397 $s .= " ($metaString)";
403 protected function setLastError( $error ) {
404 $this->error
= $error;
407 public function getLastError() {