3 * Redis-backed job queue 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 * @author Aaron Schulz
25 * Class to handle job queues stored in Redis
27 * This is faster, less resource intensive, queue that JobQueueDB.
28 * All data for a queue using this class is placed into one redis server.
30 * There are eight main redis keys used to track jobs:
31 * - l-unclaimed : A list of job IDs used for ready unclaimed jobs
32 * - z-claimed : A sorted set of (job ID, UNIX timestamp as score) used for job retries
33 * - z-abandoned : A sorted set of (job ID, UNIX timestamp as score) used for broken jobs
34 * - z-delayed : A sorted set of (job ID, UNIX timestamp as score) used for delayed jobs
35 * - h-idBySha1 : A hash of (SHA1 => job ID) for unclaimed jobs used for de-duplication
36 * - h-sha1ById : A hash of (job ID => SHA1) for unclaimed jobs used for de-duplication
37 * - h-attempts : A hash of (job ID => attempt count) used for job claiming/retries
38 * - h-data : A hash of (job ID => serialized blobs) for job storage
39 * A job ID can be in only one of z-delayed, l-unclaimed, z-claimed, and z-abandoned.
40 * If an ID appears in any of those lists, it should have a h-data entry for its ID.
41 * If a job has a SHA1 de-duplication value and its ID is in l-unclaimed or z-delayed, then
42 * there should be no other such jobs with that SHA1. Every h-idBySha1 entry has an h-sha1ById
43 * entry and every h-sha1ById must refer to an ID that is l-unclaimed. If a job has its
44 * ID in z-claimed or z-abandoned, then it must also have an h-attempts entry for its ID.
46 * Additionally, "rootjob:* keys track "root jobs" used for additional de-duplication.
47 * Aside from root job keys, all keys have no expiry, and are only removed when jobs are run.
48 * All the keys are prefixed with the relevant wiki ID information.
50 * This class requires Redis 2.6 as it makes use Lua scripts for fast atomic operations.
51 * Additionally, it should be noted that redis has different persistence modes, such
52 * as rdb snapshots, journaling, and no persistent. Appropriate configuration should be
53 * made on the servers based on what queues are using it and what tolerance they have.
59 class JobQueueRedis
extends JobQueue
{
60 /** @var RedisConnectionPool */
63 /** @var string Server address */
66 /** @var string Compression method to use */
67 protected $compression;
69 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed (7 days)
71 /** @var string Key to prefix the queue keys with (used for testing) */
76 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
77 * Note that the serializer option is ignored as "none" is always used.
78 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
79 * If a hostname is specified but no port, the standard port number
80 * 6379 will be used. Required.
81 * - compression : The type of compression to use; one of (none,gzip).
82 * @param array $params
84 public function __construct( array $params ) {
85 parent
::__construct( $params );
86 $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua
87 $this->server
= $params['redisServer'];
88 $this->compression
= isset( $params['compression'] ) ?
$params['compression'] : 'none';
89 $this->redisPool
= RedisConnectionPool
::singleton( $params['redisConfig'] );
92 protected function supportedOrders() {
93 return array( 'timestamp', 'fifo' );
96 protected function optimalOrder() {
100 protected function supportsDelayedJobs() {
105 * @see JobQueue::doIsEmpty()
107 * @throws MWException
109 protected function doIsEmpty() {
110 return $this->doGetSize() == 0;
114 * @see JobQueue::doGetSize()
116 * @throws MWException
118 protected function doGetSize() {
119 $conn = $this->getConnection();
121 return $conn->lSize( $this->getQueueKey( 'l-unclaimed' ) );
122 } catch ( RedisException
$e ) {
123 $this->throwRedisException( $this->server
, $conn, $e );
128 * @see JobQueue::doGetAcquiredCount()
130 * @throws JobQueueError
132 protected function doGetAcquiredCount() {
133 if ( $this->claimTTL
<= 0 ) {
134 return 0; // no acknowledgements
136 $conn = $this->getConnection();
138 $conn->multi( Redis
::PIPELINE
);
139 $conn->zSize( $this->getQueueKey( 'z-claimed' ) );
140 $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
142 return array_sum( $conn->exec() );
143 } catch ( RedisException
$e ) {
144 $this->throwRedisException( $this->server
, $conn, $e );
149 * @see JobQueue::doGetDelayedCount()
151 * @throws JobQueueError
153 protected function doGetDelayedCount() {
154 if ( !$this->checkDelay
) {
155 return 0; // no delayed jobs
157 $conn = $this->getConnection();
159 return $conn->zSize( $this->getQueueKey( 'z-delayed' ) );
160 } catch ( RedisException
$e ) {
161 $this->throwRedisException( $this->server
, $conn, $e );
166 * @see JobQueue::doGetAbandonedCount()
168 * @throws JobQueueError
170 protected function doGetAbandonedCount() {
171 if ( $this->claimTTL
<= 0 ) {
172 return 0; // no acknowledgements
174 $conn = $this->getConnection();
176 return $conn->zSize( $this->getQueueKey( 'z-abandoned' ) );
177 } catch ( RedisException
$e ) {
178 $this->throwRedisException( $this->server
, $conn, $e );
183 * @see JobQueue::doBatchPush()
187 * @throws JobQueueError
189 protected function doBatchPush( array $jobs, $flags ) {
190 // Convert the jobs into field maps (de-duplicated against each other)
191 $items = array(); // (job ID => job fields map)
192 foreach ( $jobs as $job ) {
193 $item = $this->getNewJobFields( $job );
194 if ( strlen( $item['sha1'] ) ) { // hash identifier => de-duplicate
195 $items[$item['sha1']] = $item;
197 $items[$item['uuid']] = $item;
201 if ( !count( $items ) ) {
202 return true; // nothing to do
205 $conn = $this->getConnection();
207 // Actually push the non-duplicate jobs into the queue...
208 if ( $flags & self
::QOS_ATOMIC
) {
209 $batches = array( $items ); // all or nothing
211 $batches = array_chunk( $items, 500 ); // avoid tying up the server
215 foreach ( $batches as $itemBatch ) {
216 $added = $this->pushBlobs( $conn, $itemBatch );
217 if ( is_int( $added ) ) {
220 $failed +
= count( $itemBatch );
224 wfDebugLog( 'JobQueueRedis', "Could not insert {$failed} {$this->type} job(s)." );
228 JobQueue
::incrStats( 'job-insert', $this->type
, count( $items ) );
229 JobQueue
::incrStats( 'job-insert-duplicate', $this->type
,
230 count( $items ) - $failed - $pushed );
231 } catch ( RedisException
$e ) {
232 $this->throwRedisException( $this->server
, $conn, $e );
239 * @param RedisConnRef $conn
240 * @param array $items List of results from JobQueueRedis::getNewJobFields()
241 * @return int Number of jobs inserted (duplicates are ignored)
242 * @throws RedisException
244 protected function pushBlobs( RedisConnRef
$conn, array $items ) {
245 $args = array(); // ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
246 foreach ( $items as $item ) {
247 $args[] = (string)$item['uuid'];
248 $args[] = (string)$item['sha1'];
249 $args[] = (string)$item['rtimestamp'];
250 $args[] = (string)$this->serialize( $item );
254 local kUnclaimed, kSha1ById, kIdBySha1, kDelayed, kData = unpack(KEYS)
255 if #ARGV % 4 ~= 0 then return redis.error_reply('Unmatched arguments') end
258 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
259 if sha1 == '' or redis.call('hExists',kIdBySha1,sha1) == 0 then
260 if 1*rtimestamp > 0 then
261 -- Insert into delayed queue (release time as score)
262 redis.call('zAdd',kDelayed,rtimestamp,id)
264 -- Insert into unclaimed queue
265 redis.call('lPush',kUnclaimed,id)
268 redis.call('hSet',kSha1ById,id,sha1)
269 redis.call('hSet',kIdBySha1,sha1,id)
271 redis.call('hSet',kData,id,blob)
277 return $conn->luaEval( $script,
280 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
281 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
282 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
283 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
284 $this->getQueueKey( 'h-data' ), # KEYS[5]
288 5 # number of first argument(s) that are keys
293 * @see JobQueue::doPop()
295 * @throws JobQueueError
297 protected function doPop() {
300 // Push ready delayed jobs into the queue every 10 jobs to spread the load.
301 // This is also done as a periodic task, but we don't want too much done at once.
302 if ( $this->checkDelay
&& mt_rand( 0, 9 ) == 0 ) {
303 $this->releaseReadyDelayedJobs();
306 $conn = $this->getConnection();
309 if ( $this->claimTTL
> 0 ) {
310 // Keep the claimed job list down for high-traffic queues
311 if ( mt_rand( 0, 99 ) == 0 ) {
312 $this->recycleAndDeleteStaleJobs();
314 $blob = $this->popAndAcquireBlob( $conn );
316 $blob = $this->popAndDeleteBlob( $conn );
318 if ( $blob === false ) {
319 break; // no jobs; nothing to do
322 JobQueue
::incrStats( 'job-pop', $this->type
);
323 $item = $this->unserialize( $blob );
324 if ( $item === false ) {
325 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
329 // If $item is invalid, recycleAndDeleteStaleJobs() will cleanup as needed
330 $job = $this->getJobFromFields( $item ); // may be false
331 } while ( !$job ); // job may be false if invalid
332 } catch ( RedisException
$e ) {
333 $this->throwRedisException( $this->server
, $conn, $e );
340 * @param RedisConnRef $conn
341 * @return array serialized string or false
342 * @throws RedisException
344 protected function popAndDeleteBlob( RedisConnRef
$conn ) {
347 local kUnclaimed, kSha1ById, kIdBySha1, kData = unpack(KEYS)
348 -- Pop an item off the queue
349 local id = redis.call('rpop',kUnclaimed)
350 if not id then return false end
351 -- Get the job data and remove it
352 local item = redis.call('hGet',kData,id)
353 redis.call('hDel',kData,id)
354 -- Allow new duplicates of this job
355 local sha1 = redis.call('hGet',kSha1ById,id)
356 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
357 redis.call('hDel',kSha1ById,id)
358 -- Return the job data
361 return $conn->luaEval( $script,
363 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
364 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
365 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
366 $this->getQueueKey( 'h-data' ), # KEYS[4]
368 4 # number of first argument(s) that are keys
373 * @param RedisConnRef $conn
374 * @return array serialized string or false
375 * @throws RedisException
377 protected function popAndAcquireBlob( RedisConnRef
$conn ) {
380 local kUnclaimed, kSha1ById, kIdBySha1, kClaimed, kAttempts, kData = unpack(KEYS)
381 -- Pop an item off the queue
382 local id = redis.call('rPop',kUnclaimed)
383 if not id then return false end
384 -- Allow new duplicates of this job
385 local sha1 = redis.call('hGet',kSha1ById,id)
386 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
387 redis.call('hDel',kSha1ById,id)
388 -- Mark the jobs as claimed and return it
389 redis.call('zAdd',kClaimed,ARGV[1],id)
390 redis.call('hIncrBy',kAttempts,id,1)
391 return redis.call('hGet',kData,id)
393 return $conn->luaEval( $script,
395 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
396 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
397 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
398 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
399 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
400 $this->getQueueKey( 'h-data' ), # KEYS[6]
401 time(), # ARGV[1] (injected to be replication-safe)
403 6 # number of first argument(s) that are keys
408 * @see JobQueue::doAck()
411 * @throws MWException|JobQueueError
413 protected function doAck( Job
$job ) {
414 if ( !isset( $job->metadata
['uuid'] ) ) {
415 throw new MWException( "Job of type '{$job->getType()}' has no UUID." );
417 if ( $this->claimTTL
> 0 ) {
418 $conn = $this->getConnection();
422 local kClaimed, kAttempts, kData = unpack(KEYS)
423 -- Unmark the job as claimed
424 redis.call('zRem',kClaimed,ARGV[1])
425 redis.call('hDel',kAttempts,ARGV[1])
426 -- Delete the job data itself
427 return redis.call('hDel',kData,ARGV[1])
429 $res = $conn->luaEval( $script,
431 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
432 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
433 $this->getQueueKey( 'h-data' ), # KEYS[3]
434 $job->metadata
['uuid'] # ARGV[1]
436 3 # number of first argument(s) that are keys
440 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
444 } catch ( RedisException
$e ) {
445 $this->throwRedisException( $this->server
, $conn, $e );
453 * @see JobQueue::doDeduplicateRootJob()
456 * @throws MWException|JobQueueError
458 protected function doDeduplicateRootJob( Job
$job ) {
459 if ( !$job->hasRootJobParams() ) {
460 throw new MWException( "Cannot register root job; missing parameters." );
462 $params = $job->getRootJobParams();
464 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
466 $conn = $this->getConnection();
468 $timestamp = $conn->get( $key ); // current last timestamp of this job
469 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
470 return true; // a newer version of this root job was enqueued
473 // Update the timestamp of the last root job started at the location...
474 return $conn->set( $key, $params['rootJobTimestamp'], self
::ROOTJOB_TTL
); // 2 weeks
475 } catch ( RedisException
$e ) {
476 $this->throwRedisException( $this->server
, $conn, $e );
481 * @see JobQueue::doIsRootJobOldDuplicate()
484 * @throws JobQueueError
486 protected function doIsRootJobOldDuplicate( Job
$job ) {
487 if ( !$job->hasRootJobParams() ) {
488 return false; // job has no de-deplication info
490 $params = $job->getRootJobParams();
492 $conn = $this->getConnection();
494 // Get the last time this root job was enqueued
495 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
496 } catch ( RedisException
$e ) {
497 $this->throwRedisException( $this->server
, $conn, $e );
500 // Check if a new root job was started at the location after this one's...
501 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
505 * @see JobQueue::doDelete()
507 * @throws JobQueueError
509 protected function doDelete() {
510 static $props = array( 'l-unclaimed', 'z-claimed', 'z-abandoned',
511 'z-delayed', 'h-idBySha1', 'h-sha1ById', 'h-attempts', 'h-data' );
513 $conn = $this->getConnection();
516 foreach ( $props as $prop ) {
517 $keys[] = $this->getQueueKey( $prop );
520 return ( $conn->delete( $keys ) !== false );
521 } catch ( RedisException
$e ) {
522 $this->throwRedisException( $this->server
, $conn, $e );
527 * @see JobQueue::getAllQueuedJobs()
530 public function getAllQueuedJobs() {
531 $conn = $this->getConnection();
535 return new MappedIterator(
536 $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 ),
537 function ( $uid ) use ( $that, $conn ) {
538 return $that->getJobFromUidInternal( $uid, $conn );
540 array( 'accept' => function ( $job ) {
541 return is_object( $job );
544 } catch ( RedisException
$e ) {
545 $this->throwRedisException( $this->server
, $conn, $e );
550 * @see JobQueue::getAllQueuedJobs()
553 public function getAllDelayedJobs() {
554 $conn = $this->getConnection();
558 return new MappedIterator( // delayed jobs
559 $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 ),
560 function ( $uid ) use ( $that, $conn ) {
561 return $that->getJobFromUidInternal( $uid, $conn );
563 array( 'accept' => function ( $job ) {
564 return is_object( $job );
567 } catch ( RedisException
$e ) {
568 $this->throwRedisException( $this->server
, $conn, $e );
572 public function getCoalesceLocationInternal() {
573 return "RedisServer:" . $this->server
;
576 protected function doGetSiblingQueuesWithJobs( array $types ) {
577 return array_keys( array_filter( $this->doGetSiblingQueueSizes( $types ) ) );
580 protected function doGetSiblingQueueSizes( array $types ) {
581 $sizes = array(); // (type => size)
582 $types = array_values( $types ); // reindex
584 $conn = $this->getConnection();
585 $conn->multi( Redis
::PIPELINE
);
586 foreach ( $types as $type ) {
587 $conn->lSize( $this->getQueueKey( 'l-unclaimed', $type ) );
589 $res = $conn->exec();
590 if ( is_array( $res ) ) {
591 foreach ( $res as $i => $size ) {
592 $sizes[$types[$i]] = $size;
595 } catch ( RedisException
$e ) {
596 $this->throwRedisException( $this->server
, $conn, $e );
603 * This function should not be called outside JobQueueRedis
606 * @param $conn RedisConnRef
607 * @return Job|bool Returns false if the job does not exist
608 * @throws MWException|JobQueueError
610 public function getJobFromUidInternal( $uid, RedisConnRef
$conn ) {
612 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
613 if ( $data === false ) {
614 return false; // not found
616 $item = $this->unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
617 if ( !is_array( $item ) ) { // this shouldn't happen
618 throw new MWException( "Could not find job with ID '$uid'." );
620 $title = Title
::makeTitle( $item['namespace'], $item['title'] );
621 $job = Job
::factory( $item['type'], $title, $item['params'] );
622 $job->metadata
['uuid'] = $item['uuid'];
625 } catch ( RedisException
$e ) {
626 $this->throwRedisException( $this->server
, $conn, $e );
631 * Release any ready delayed jobs into the queue
633 * @return int Number of jobs released
634 * @throws JobQueueError
636 public function releaseReadyDelayedJobs() {
639 $conn = $this->getConnection();
643 local kDelayed, kUnclaimed = unpack(KEYS)
644 -- Get the list of ready delayed jobs, sorted by readiness
645 local ids = redis.call('zRangeByScore',kDelayed,0,ARGV[1])
646 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
647 for k,id in ipairs(ids) do
648 redis.call('lPush',kUnclaimed,id)
649 redis.call('zRem',kDelayed,id)
653 $count +
= (int)$conn->luaEval( $script,
655 $this->getQueueKey( 'z-delayed' ), // KEYS[1]
656 $this->getQueueKey( 'l-unclaimed' ), // KEYS[2]
657 time() // ARGV[1]; max "delay until" UNIX timestamp
659 2 # first two arguments are keys
661 } catch ( RedisException
$e ) {
662 $this->throwRedisException( $this->server
, $conn, $e );
669 * Recycle or destroy any jobs that have been claimed for too long
671 * @return int Number of jobs recycled/deleted
672 * @throws MWException|JobQueueError
674 public function recycleAndDeleteStaleJobs() {
675 if ( $this->claimTTL
<= 0 ) { // sanity
676 throw new MWException( "Cannot recycle jobs since acknowledgements are disabled." );
679 // For each job item that can be retried, we need to add it back to the
680 // main queue and remove it from the list of currenty claimed job items.
681 // For those that cannot, they are marked as dead and kept around for
682 // investigation and manual job restoration but are eventually deleted.
683 $conn = $this->getConnection();
688 local kClaimed, kAttempts, kUnclaimed, kData, kAbandoned = unpack(KEYS)
689 local released,abandoned,pruned = 0,0,0
690 -- Get all non-dead jobs that have an expired claim on them.
691 -- The score for each item is the last claim timestamp (UNIX).
692 local staleClaims = redis.call('zRangeByScore',kClaimed,0,ARGV[1])
693 for k,id in ipairs(staleClaims) do
694 local timestamp = redis.call('zScore',kClaimed,id)
695 local attempts = redis.call('hGet',kAttempts,id)
696 if attempts < ARGV[3] then
697 -- Claim expired and retries left: re-enqueue the job
698 redis.call('lPush',kUnclaimed,id)
699 redis.call('hIncrBy',kAttempts,id,1)
700 released = released + 1
702 -- Claim expired and no retries left: mark the job as dead
703 redis.call('zAdd',kAbandoned,timestamp,id)
704 abandoned = abandoned + 1
706 redis.call('zRem',kClaimed,id)
708 -- Get all of the dead jobs that have been marked as dead for too long.
709 -- The score for each item is the last claim timestamp (UNIX).
710 local deadClaims = redis.call('zRangeByScore',kAbandoned,0,ARGV[2])
711 for k,id in ipairs(deadClaims) do
712 -- Stale and out of retries: remove any traces of the job
713 redis.call('zRem',kAbandoned,id)
714 redis.call('hDel',kAttempts,id)
715 redis.call('hDel',kData,id)
718 return {released,abandoned,pruned}
720 $res = $conn->luaEval( $script,
722 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
723 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
724 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
725 $this->getQueueKey( 'h-data' ), # KEYS[4]
726 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
727 $now - $this->claimTTL
, # ARGV[1]
728 $now - self
::MAX_AGE_PRUNE
, # ARGV[2]
729 $this->maxTries
# ARGV[3]
731 5 # number of first argument(s) that are keys
734 list( $released, $abandoned, $pruned ) = $res;
735 $count +
= $released +
$pruned;
736 JobQueue
::incrStats( 'job-recycle', $this->type
, $released );
737 JobQueue
::incrStats( 'job-abandon', $this->type
, $abandoned );
739 } catch ( RedisException
$e ) {
740 $this->throwRedisException( $this->server
, $conn, $e );
749 protected function doGetPeriodicTasks() {
751 if ( $this->claimTTL
> 0 ) {
752 $tasks['recycleAndDeleteStaleJobs'] = array(
753 'callback' => array( $this, 'recycleAndDeleteStaleJobs' ),
754 'period' => ceil( $this->claimTTL
/ 2 )
757 if ( $this->checkDelay
) {
758 $tasks['releaseReadyDelayedJobs'] = array(
759 'callback' => array( $this, 'releaseReadyDelayedJobs' ),
760 'period' => 300 // 5 minutes
771 protected function getNewJobFields( Job
$job ) {
773 // Fields that describe the nature of the job
774 'type' => $job->getType(),
775 'namespace' => $job->getTitle()->getNamespace(),
776 'title' => $job->getTitle()->getDBkey(),
777 'params' => $job->getParams(),
778 // Some jobs cannot run until a "release timestamp"
779 'rtimestamp' => $job->getReleaseTimestamp() ?
: 0,
780 // Additional job metadata
781 'uuid' => UIDGenerator
::newRawUUIDv4( UIDGenerator
::QUICK_RAND
),
782 'sha1' => $job->ignoreDuplicates()
783 ?
wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
785 'timestamp' => time() // UNIX timestamp
790 * @param $fields array
793 protected function getJobFromFields( array $fields ) {
794 $title = Title
::makeTitleSafe( $fields['namespace'], $fields['title'] );
796 $job = Job
::factory( $fields['type'], $title, $fields['params'] );
797 $job->metadata
['uuid'] = $fields['uuid'];
806 * @param array $fields
807 * @return string Serialized and possibly compressed version of $fields
809 protected function serialize( array $fields ) {
810 $blob = serialize( $fields );
811 if ( $this->compression
=== 'gzip'
812 && strlen( $blob ) >= 1024
813 && function_exists( 'gzdeflate' )
815 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
816 $blobz = serialize( $object );
818 return ( strlen( $blobz ) < strlen( $blob ) ) ?
$blobz : $blob;
825 * @param string $blob
826 * @return array|bool Unserialized version of $blob or false
828 protected function unserialize( $blob ) {
829 $fields = unserialize( $blob );
830 if ( is_object( $fields ) ) {
831 if ( $fields->enc
=== 'gzip' && function_exists( 'gzinflate' ) ) {
832 $fields = unserialize( gzinflate( $fields->blob
) );
838 return is_array( $fields ) ?
$fields : false;
842 * Get a connection to the server that handles all sub-queues for this queue
844 * @return RedisConnRef
845 * @throws JobQueueConnectionError
847 protected function getConnection() {
848 $conn = $this->redisPool
->getConnection( $this->server
);
850 throw new JobQueueConnectionError( "Unable to connect to redis server." );
857 * @param $server string
858 * @param $conn RedisConnRef
859 * @param $e RedisException
860 * @throws JobQueueError
862 protected function throwRedisException( $server, RedisConnRef
$conn, $e ) {
863 $this->redisPool
->handleException( $server, $conn, $e );
864 throw new JobQueueError( "Redis server error: {$e->getMessage()}\n" );
868 * @param $prop string
869 * @param $type string|null
872 private function getQueueKey( $prop, $type = null ) {
873 $type = is_string( $type ) ?
$type : $this->type
;
874 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
875 if ( strlen( $this->key
) ) { // namespaced queue (for testing)
876 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $this->key
, $prop );
878 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $prop );
886 public function setTestingPrefix( $key ) {