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( $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( $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( $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( $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; // 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)." );
226 throw new RedisException( "Could not insert {$failed} {$this->type} job(s)." );
228 JobQueue
::incrStats( 'job-insert', $this->type
, count( $items ), $this->wiki
);
229 JobQueue
::incrStats( 'job-insert-duplicate', $this->type
,
230 count( $items ) - $failed - $pushed, $this->wiki
);
231 } catch ( RedisException
$e ) {
232 $this->throwRedisException( $conn, $e );
237 * @param RedisConnRef $conn
238 * @param array $items List of results from JobQueueRedis::getNewJobFields()
239 * @return int Number of jobs inserted (duplicates are ignored)
240 * @throws RedisException
242 protected function pushBlobs( RedisConnRef
$conn, array $items ) {
243 $args = array(); // ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
244 foreach ( $items as $item ) {
245 $args[] = (string)$item['uuid'];
246 $args[] = (string)$item['sha1'];
247 $args[] = (string)$item['rtimestamp'];
248 $args[] = (string)$this->serialize( $item );
252 local kUnclaimed, kSha1ById, kIdBySha1, kDelayed, kData = unpack(KEYS)
253 if #ARGV % 4 ~= 0 then return redis.error_reply('Unmatched arguments') end
256 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
257 if sha1 == '' or redis.call('hExists',kIdBySha1,sha1) == 0 then
258 if 1*rtimestamp > 0 then
259 -- Insert into delayed queue (release time as score)
260 redis.call('zAdd',kDelayed,rtimestamp,id)
262 -- Insert into unclaimed queue
263 redis.call('lPush',kUnclaimed,id)
266 redis.call('hSet',kSha1ById,id,sha1)
267 redis.call('hSet',kIdBySha1,sha1,id)
269 redis.call('hSet',kData,id,blob)
275 return $conn->luaEval( $script,
278 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
279 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
280 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
281 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
282 $this->getQueueKey( 'h-data' ), # KEYS[5]
286 5 # number of first argument(s) that are keys
291 * @see JobQueue::doPop()
293 * @throws JobQueueError
295 protected function doPop() {
298 // Push ready delayed jobs into the queue every 10 jobs to spread the load.
299 // This is also done as a periodic task, but we don't want too much done at once.
300 if ( $this->checkDelay
&& mt_rand( 0, 9 ) == 0 ) {
301 $this->recyclePruneAndUndelayJobs();
304 $conn = $this->getConnection();
307 if ( $this->claimTTL
> 0 ) {
308 // Keep the claimed job list down for high-traffic queues
309 if ( mt_rand( 0, 99 ) == 0 ) {
310 $this->recyclePruneAndUndelayJobs();
312 $blob = $this->popAndAcquireBlob( $conn );
314 $blob = $this->popAndDeleteBlob( $conn );
316 if ( $blob === false ) {
317 break; // no jobs; nothing to do
320 JobQueue
::incrStats( 'job-pop', $this->type
, 1, $this->wiki
);
321 $item = $this->unserialize( $blob );
322 if ( $item === false ) {
323 wfDebugLog( 'JobQueueRedis', "Could not unserialize {$this->type} job." );
327 // If $item is invalid, recyclePruneAndUndelayJobs() will cleanup as needed
328 $job = $this->getJobFromFields( $item ); // may be false
329 } while ( !$job ); // job may be false if invalid
330 } catch ( RedisException
$e ) {
331 $this->throwRedisException( $conn, $e );
338 * @param RedisConnRef $conn
339 * @return array Serialized string or false
340 * @throws RedisException
342 protected function popAndDeleteBlob( RedisConnRef
$conn ) {
345 local kUnclaimed, kSha1ById, kIdBySha1, kData = unpack(KEYS)
346 -- Pop an item off the queue
347 local id = redis.call('rpop',kUnclaimed)
348 if not id then return false end
349 -- Get the job data and remove it
350 local item = redis.call('hGet',kData,id)
351 redis.call('hDel',kData,id)
352 -- Allow new duplicates of this job
353 local sha1 = redis.call('hGet',kSha1ById,id)
354 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
355 redis.call('hDel',kSha1ById,id)
356 -- Return the job data
359 return $conn->luaEval( $script,
361 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
362 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
363 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
364 $this->getQueueKey( 'h-data' ), # KEYS[4]
366 4 # number of first argument(s) that are keys
371 * @param RedisConnRef $conn
372 * @return array Serialized string or false
373 * @throws RedisException
375 protected function popAndAcquireBlob( RedisConnRef
$conn ) {
378 local kUnclaimed, kSha1ById, kIdBySha1, kClaimed, kAttempts, kData = unpack(KEYS)
379 -- Pop an item off the queue
380 local id = redis.call('rPop',kUnclaimed)
381 if not id then return false end
382 -- Allow new duplicates of this job
383 local sha1 = redis.call('hGet',kSha1ById,id)
384 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
385 redis.call('hDel',kSha1ById,id)
386 -- Mark the jobs as claimed and return it
387 redis.call('zAdd',kClaimed,ARGV[1],id)
388 redis.call('hIncrBy',kAttempts,id,1)
389 return redis.call('hGet',kData,id)
391 return $conn->luaEval( $script,
393 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
394 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
395 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
396 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
397 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
398 $this->getQueueKey( 'h-data' ), # KEYS[6]
399 time(), # ARGV[1] (injected to be replication-safe)
401 6 # number of first argument(s) that are keys
406 * @see JobQueue::doAck()
409 * @throws MWException|JobQueueError
411 protected function doAck( Job
$job ) {
412 if ( !isset( $job->metadata
['uuid'] ) ) {
413 throw new MWException( "Job of type '{$job->getType()}' has no UUID." );
415 if ( $this->claimTTL
> 0 ) {
416 $conn = $this->getConnection();
420 local kClaimed, kAttempts, kData = unpack(KEYS)
421 -- Unmark the job as claimed
422 redis.call('zRem',kClaimed,ARGV[1])
423 redis.call('hDel',kAttempts,ARGV[1])
424 -- Delete the job data itself
425 return redis.call('hDel',kData,ARGV[1])
427 $res = $conn->luaEval( $script,
429 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
430 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
431 $this->getQueueKey( 'h-data' ), # KEYS[3]
432 $job->metadata
['uuid'] # ARGV[1]
434 3 # number of first argument(s) that are keys
438 wfDebugLog( 'JobQueueRedis', "Could not acknowledge {$this->type} job." );
442 } catch ( RedisException
$e ) {
443 $this->throwRedisException( $conn, $e );
451 * @see JobQueue::doDeduplicateRootJob()
454 * @throws MWException|JobQueueError
456 protected function doDeduplicateRootJob( Job
$job ) {
457 if ( !$job->hasRootJobParams() ) {
458 throw new MWException( "Cannot register root job; missing parameters." );
460 $params = $job->getRootJobParams();
462 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
464 $conn = $this->getConnection();
466 $timestamp = $conn->get( $key ); // current last timestamp of this job
467 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
468 return true; // a newer version of this root job was enqueued
471 // Update the timestamp of the last root job started at the location...
472 return $conn->set( $key, $params['rootJobTimestamp'], self
::ROOTJOB_TTL
); // 2 weeks
473 } catch ( RedisException
$e ) {
474 $this->throwRedisException( $conn, $e );
479 * @see JobQueue::doIsRootJobOldDuplicate()
482 * @throws JobQueueError
484 protected function doIsRootJobOldDuplicate( Job
$job ) {
485 if ( !$job->hasRootJobParams() ) {
486 return false; // job has no de-deplication info
488 $params = $job->getRootJobParams();
490 $conn = $this->getConnection();
492 // Get the last time this root job was enqueued
493 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'] ) );
494 } catch ( RedisException
$e ) {
495 $this->throwRedisException( $conn, $e );
498 // Check if a new root job was started at the location after this one's...
499 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
503 * @see JobQueue::doDelete()
505 * @throws JobQueueError
507 protected function doDelete() {
508 static $props = array( 'l-unclaimed', 'z-claimed', 'z-abandoned',
509 'z-delayed', 'h-idBySha1', 'h-sha1ById', 'h-attempts', 'h-data' );
511 $conn = $this->getConnection();
514 foreach ( $props as $prop ) {
515 $keys[] = $this->getQueueKey( $prop );
518 return ( $conn->delete( $keys ) !== false );
519 } catch ( RedisException
$e ) {
520 $this->throwRedisException( $conn, $e );
525 * @see JobQueue::getAllQueuedJobs()
528 public function getAllQueuedJobs() {
529 $conn = $this->getConnection();
533 return new MappedIterator(
534 $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 ),
535 function ( $uid ) use ( $that, $conn ) {
536 return $that->getJobFromUidInternal( $uid, $conn );
538 array( 'accept' => function ( $job ) {
539 return is_object( $job );
542 } catch ( RedisException
$e ) {
543 $this->throwRedisException( $conn, $e );
548 * @see JobQueue::getAllQueuedJobs()
551 public function getAllDelayedJobs() {
552 $conn = $this->getConnection();
556 return new MappedIterator( // delayed jobs
557 $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 ),
558 function ( $uid ) use ( $that, $conn ) {
559 return $that->getJobFromUidInternal( $uid, $conn );
561 array( 'accept' => function ( $job ) {
562 return is_object( $job );
565 } catch ( RedisException
$e ) {
566 $this->throwRedisException( $conn, $e );
570 public function getCoalesceLocationInternal() {
571 return "RedisServer:" . $this->server
;
574 protected function doGetSiblingQueuesWithJobs( array $types ) {
575 return array_keys( array_filter( $this->doGetSiblingQueueSizes( $types ) ) );
578 protected function doGetSiblingQueueSizes( array $types ) {
579 $sizes = array(); // (type => size)
580 $types = array_values( $types ); // reindex
581 $conn = $this->getConnection();
583 $conn->multi( Redis
::PIPELINE
);
584 foreach ( $types as $type ) {
585 $conn->lSize( $this->getQueueKey( 'l-unclaimed', $type ) );
587 $res = $conn->exec();
588 if ( is_array( $res ) ) {
589 foreach ( $res as $i => $size ) {
590 $sizes[$types[$i]] = $size;
593 } catch ( RedisException
$e ) {
594 $this->throwRedisException( $conn, $e );
601 * This function should not be called outside JobQueueRedis
604 * @param RedisConnRef $conn
605 * @return Job|bool Returns false if the job does not exist
606 * @throws MWException|JobQueueError
608 public function getJobFromUidInternal( $uid, RedisConnRef
$conn ) {
610 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
611 if ( $data === false ) {
612 return false; // not found
614 $item = $this->unserialize( $conn->hGet( $this->getQueueKey( 'h-data' ), $uid ) );
615 if ( !is_array( $item ) ) { // this shouldn't happen
616 throw new MWException( "Could not find job with ID '$uid'." );
618 $title = Title
::makeTitle( $item['namespace'], $item['title'] );
619 $job = Job
::factory( $item['type'], $title, $item['params'] );
620 $job->metadata
['uuid'] = $item['uuid'];
623 } catch ( RedisException
$e ) {
624 $this->throwRedisException( $conn, $e );
629 * Recycle or destroy any jobs that have been claimed for too long
630 * and release any ready delayed jobs into the queue
632 * @return int Number of jobs recycled/deleted/undelayed
633 * @throws MWException|JobQueueError
635 public function recyclePruneAndUndelayJobs() {
637 // For each job item that can be retried, we need to add it back to the
638 // main queue and remove it from the list of currenty claimed job items.
639 // For those that cannot, they are marked as dead and kept around for
640 // investigation and manual job restoration but are eventually deleted.
641 $conn = $this->getConnection();
646 local kClaimed, kAttempts, kUnclaimed, kData, kAbandoned, kDelayed = unpack(KEYS)
647 local released,abandoned,pruned,undelayed = 0,0,0,0
648 -- Get all non-dead jobs that have an expired claim on them.
649 -- The score for each item is the last claim timestamp (UNIX).
650 local staleClaims = redis.call('zRangeByScore',kClaimed,0,ARGV[1])
651 for k,id in ipairs(staleClaims) do
652 local timestamp = redis.call('zScore',kClaimed,id)
653 local attempts = redis.call('hGet',kAttempts,id)
654 if attempts < ARGV[3] then
655 -- Claim expired and retries left: re-enqueue the job
656 redis.call('lPush',kUnclaimed,id)
657 redis.call('hIncrBy',kAttempts,id,1)
658 released = released + 1
660 -- Claim expired and no retries left: mark the job as dead
661 redis.call('zAdd',kAbandoned,timestamp,id)
662 abandoned = abandoned + 1
664 redis.call('zRem',kClaimed,id)
666 -- Get all of the dead jobs that have been marked as dead for too long.
667 -- The score for each item is the last claim timestamp (UNIX).
668 local deadClaims = redis.call('zRangeByScore',kAbandoned,0,ARGV[2])
669 for k,id in ipairs(deadClaims) do
670 -- Stale and out of retries: remove any traces of the job
671 redis.call('zRem',kAbandoned,id)
672 redis.call('hDel',kAttempts,id)
673 redis.call('hDel',kData,id)
676 -- Get the list of ready delayed jobs, sorted by readiness (UNIX timestamp)
677 local ids = redis.call('zRangeByScore',kDelayed,0,ARGV[4])
678 -- Migrate the jobs from the "delayed" set to the "unclaimed" list
679 for k,id in ipairs(ids) do
680 redis.call('lPush',kUnclaimed,id)
681 redis.call('zRem',kDelayed,id)
684 return {released,abandoned,pruned,undelayed}
686 $res = $conn->luaEval( $script,
688 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
689 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
690 $this->getQueueKey( 'l-unclaimed' ), # KEYS[3]
691 $this->getQueueKey( 'h-data' ), # KEYS[4]
692 $this->getQueueKey( 'z-abandoned' ), # KEYS[5]
693 $this->getQueueKey( 'z-delayed' ), # KEYS[6]
694 $now - $this->claimTTL
, # ARGV[1]
695 $now - self
::MAX_AGE_PRUNE
, # ARGV[2]
696 $this->maxTries
, # ARGV[3]
699 6 # number of first argument(s) that are keys
702 list( $released, $abandoned, $pruned, $undelayed ) = $res;
703 $count +
= $released +
$pruned +
$undelayed;
704 JobQueue
::incrStats( 'job-recycle', $this->type
, $released, $this->wiki
);
705 JobQueue
::incrStats( 'job-abandon', $this->type
, $abandoned, $this->wiki
);
707 } catch ( RedisException
$e ) {
708 $this->throwRedisException( $conn, $e );
717 protected function doGetPeriodicTasks() {
718 $periods = array( 3600 ); // standard cleanup (useful on config change)
719 if ( $this->claimTTL
> 0 ) {
720 $periods[] = ceil( $this->claimTTL
/ 2 ); // avoid bad timing
722 if ( $this->checkDelay
) {
723 $periods[] = 300; // 5 minutes
725 $period = min( $periods );
726 $period = max( $period, 30 ); // sanity
729 'recyclePruneAndUndelayJobs' => array(
730 'callback' => array( $this, 'recyclePruneAndUndelayJobs' ),
737 * @param IJobSpecification $job
740 protected function getNewJobFields( IJobSpecification
$job ) {
742 // Fields that describe the nature of the job
743 'type' => $job->getType(),
744 'namespace' => $job->getTitle()->getNamespace(),
745 'title' => $job->getTitle()->getDBkey(),
746 'params' => $job->getParams(),
747 // Some jobs cannot run until a "release timestamp"
748 'rtimestamp' => $job->getReleaseTimestamp() ?
: 0,
749 // Additional job metadata
750 'uuid' => UIDGenerator
::newRawUUIDv4( UIDGenerator
::QUICK_RAND
),
751 'sha1' => $job->ignoreDuplicates()
752 ?
wfBaseConvert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
754 'timestamp' => time() // UNIX timestamp
759 * @param array $fields
762 protected function getJobFromFields( array $fields ) {
763 $title = Title
::makeTitleSafe( $fields['namespace'], $fields['title'] );
765 $job = Job
::factory( $fields['type'], $title, $fields['params'] );
766 $job->metadata
['uuid'] = $fields['uuid'];
775 * @param array $fields
776 * @return string Serialized and possibly compressed version of $fields
778 protected function serialize( array $fields ) {
779 $blob = serialize( $fields );
780 if ( $this->compression
=== 'gzip'
781 && strlen( $blob ) >= 1024
782 && function_exists( 'gzdeflate' )
784 $object = (object)array( 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' );
785 $blobz = serialize( $object );
787 return ( strlen( $blobz ) < strlen( $blob ) ) ?
$blobz : $blob;
794 * @param string $blob
795 * @return array|bool Unserialized version of $blob or false
797 protected function unserialize( $blob ) {
798 $fields = unserialize( $blob );
799 if ( is_object( $fields ) ) {
800 if ( $fields->enc
=== 'gzip' && function_exists( 'gzinflate' ) ) {
801 $fields = unserialize( gzinflate( $fields->blob
) );
807 return is_array( $fields ) ?
$fields : false;
811 * Get a connection to the server that handles all sub-queues for this queue
813 * @return RedisConnRef
814 * @throws JobQueueConnectionError
816 protected function getConnection() {
817 $conn = $this->redisPool
->getConnection( $this->server
);
819 throw new JobQueueConnectionError( "Unable to connect to redis server." );
826 * @param RedisConnRef $conn
827 * @param RedisException $e
828 * @throws JobQueueError
830 protected function throwRedisException( RedisConnRef
$conn, $e ) {
831 $this->redisPool
->handleError( $conn, $e );
832 throw new JobQueueError( "Redis server error: {$e->getMessage()}\n" );
836 * @param string $prop
837 * @param string|null $type
840 private function getQueueKey( $prop, $type = null ) {
841 $type = is_string( $type ) ?
$type : $this->type
;
842 list( $db, $prefix ) = wfSplitWikiID( $this->wiki
);
843 if ( strlen( $this->key
) ) { // namespaced queue (for testing)
844 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $this->key
, $prop );
846 return wfForeignMemcKey( $db, $prefix, 'jobqueue', $type, $prop );
854 public function setTestingPrefix( $key ) {