Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / jobqueue / JobQueueRedis.php
blob3cff313b56e4350fdf7bb52b55094436bcce25fd
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
21 use MediaWiki\Logger\LoggerFactory;
22 use MediaWiki\WikiMap\WikiMap;
23 use Psr\Log\LoggerInterface;
24 use Wikimedia\ObjectCache\RedisConnectionPool;
25 use Wikimedia\ObjectCache\RedisConnRef;
27 /**
28 * Redis-backed job queue storage.
30 * This is a faster and less resource-intensive job queue than JobQueueDB.
31 * All data for a queue using this class is placed into one redis server.
33 * When used on a wiki farm, you can optionally use the `redisJobRunnerService` background
34 * service from the `mediawiki/services/jobrunner.git` repository, to run jobs from a central
35 * system rather than per-wiki via one of the default job runners (e.g. maintenance/runJobs.php).
37 * There are eight main redis keys (per queue) used to track jobs:
38 * - l-unclaimed : A list of job IDs used for ready unclaimed jobs
39 * - z-claimed : A sorted set of (job ID, UNIX timestamp as score) used for job retries
40 * - z-abandoned : A sorted set of (job ID, UNIX timestamp as score) used for broken jobs
41 * - z-delayed : A sorted set of (job ID, UNIX timestamp as score) used for delayed jobs
42 * - h-idBySha1 : A hash of (SHA1 => job ID) for unclaimed jobs used for de-duplication
43 * - h-sha1ById : A hash of (job ID => SHA1) for unclaimed jobs used for de-duplication
44 * - h-attempts : A hash of (job ID => attempt count) used for job claiming/retries
45 * - h-data : A hash of (job ID => serialized blobs) for job storage
47 * A job ID can be in only one of z-delayed, l-unclaimed, z-claimed, and z-abandoned.
48 * If an ID appears in any of those lists, it should have a h-data entry for its ID.
49 * If a job has a SHA1 de-duplication value and its ID is in l-unclaimed or z-delayed, then
50 * there should be no other such jobs with that SHA1. Every h-idBySha1 entry has an h-sha1ById
51 * entry and every h-sha1ById must refer to an ID that is l-unclaimed. If a job has its
52 * ID in z-claimed or z-abandoned, then it must also have an h-attempts entry for its ID.
54 * The following keys are used to track queue states:
55 * - s-queuesWithJobs : A set of all queues with non-abandoned jobs
57 * The background service takes care of undelaying, recycling, and pruning jobs as well as
58 * removing s-queuesWithJobs entries as queues empty.
60 * Additionally, "rootjob:* keys track "root jobs" used for additional de-duplication.
61 * Aside from root job keys, all keys have no expiry, and are only removed when jobs are run.
62 * All the keys are prefixed with the relevant wiki ID information.
64 * This class requires Redis 2.6 or later as it uses Lua scripting for fast atomic operations.
65 * Additionally, it should be noted that redis has different persistence modes, such
66 * as rdb snapshots, journaling, or no persistence. Appropriate configuration should be
67 * made on the servers based on what queues are using it and what tolerance they have.
69 * @since 1.22
70 * @ingroup JobQueue
71 * @ingroup Redis
73 class JobQueueRedis extends JobQueue {
74 /** @var RedisConnectionPool */
75 protected $redisPool;
76 /** @var LoggerInterface */
77 protected $logger;
79 /** @var string Server address */
80 protected $server;
81 /** @var string Compression method to use */
82 protected $compression;
84 private const MAX_PUSH_SIZE = 25; // avoid tying up the server
86 /**
87 * @param array $params Possible keys:
88 * - redisConfig : An array of parameters to RedisConnectionPool::__construct().
89 * Note that the serializer option is ignored as "none" is always used.
90 * - redisServer : A hostname/port combination or the absolute path of a UNIX socket.
91 * If a hostname is specified but no port, the standard port number
92 * 6379 will be used. Required.
93 * - compression : The type of compression to use; one of (none,gzip).
94 * - daemonized : Set to true if the redisJobRunnerService runs in the background.
95 * This will disable job recycling/undelaying from the MediaWiki side
96 * to avoid redundancy and out-of-sync configuration.
98 public function __construct( array $params ) {
99 parent::__construct( $params );
100 $params['redisConfig']['serializer'] = 'none'; // make it easy to use Lua
101 $this->server = $params['redisServer'];
102 $this->compression = $params['compression'] ?? 'none';
103 $this->redisPool = RedisConnectionPool::singleton( $params['redisConfig'] );
104 if ( empty( $params['daemonized'] ) ) {
105 throw new InvalidArgumentException(
106 "Non-daemonized mode is no longer supported. Please install the " .
107 "mediawiki/services/jobrunner service and update \$wgJobTypeConf as needed." );
109 $this->logger = LoggerFactory::getInstance( 'redis' );
112 protected function supportedOrders() {
113 return [ 'timestamp', 'fifo' ];
116 protected function optimalOrder() {
117 return 'fifo';
120 protected function supportsDelayedJobs() {
121 return true;
125 * @see JobQueue::doIsEmpty()
126 * @return bool
127 * @throws JobQueueError
129 protected function doIsEmpty() {
130 return $this->doGetSize() == 0;
134 * @see JobQueue::doGetSize()
135 * @return int
136 * @throws JobQueueError
138 protected function doGetSize() {
139 $conn = $this->getConnection();
140 try {
141 return $conn->lLen( $this->getQueueKey( 'l-unclaimed' ) );
142 } catch ( RedisException $e ) {
143 throw $this->handleErrorAndMakeException( $conn, $e );
148 * @see JobQueue::doGetAcquiredCount()
149 * @return int
150 * @throws JobQueueError
152 protected function doGetAcquiredCount() {
153 $conn = $this->getConnection();
154 try {
155 $conn->multi( Redis::PIPELINE );
156 $conn->zCard( $this->getQueueKey( 'z-claimed' ) );
157 $conn->zCard( $this->getQueueKey( 'z-abandoned' ) );
159 return array_sum( $conn->exec() );
160 } catch ( RedisException $e ) {
161 throw $this->handleErrorAndMakeException( $conn, $e );
166 * @see JobQueue::doGetDelayedCount()
167 * @return int
168 * @throws JobQueueError
170 protected function doGetDelayedCount() {
171 $conn = $this->getConnection();
172 try {
173 return $conn->zCard( $this->getQueueKey( 'z-delayed' ) );
174 } catch ( RedisException $e ) {
175 throw $this->handleErrorAndMakeException( $conn, $e );
180 * @see JobQueue::doGetAbandonedCount()
181 * @return int
182 * @throws JobQueueError
184 protected function doGetAbandonedCount() {
185 $conn = $this->getConnection();
186 try {
187 return $conn->zCard( $this->getQueueKey( 'z-abandoned' ) );
188 } catch ( RedisException $e ) {
189 throw $this->handleErrorAndMakeException( $conn, $e );
194 * @see JobQueue::doBatchPush()
195 * @param IJobSpecification[] $jobs
196 * @param int $flags
197 * @return void
198 * @throws JobQueueError
200 protected function doBatchPush( array $jobs, $flags ) {
201 // Convert the jobs into field maps (de-duplicated against each other)
202 $items = []; // (job ID => job fields map)
203 foreach ( $jobs as $job ) {
204 $item = $this->getNewJobFields( $job );
205 if ( strlen( $item['sha1'] ) ) { // hash identifier => de-duplicate
206 $items[$item['sha1']] = $item;
207 } else {
208 $items[$item['uuid']] = $item;
212 if ( $items === [] ) {
213 return; // nothing to do
216 $conn = $this->getConnection();
217 try {
218 // Actually push the non-duplicate jobs into the queue...
219 if ( $flags & self::QOS_ATOMIC ) {
220 $batches = [ $items ]; // all or nothing
221 } else {
222 $batches = array_chunk( $items, self::MAX_PUSH_SIZE );
224 $failed = 0;
225 $pushed = 0;
226 foreach ( $batches as $itemBatch ) {
227 $added = $this->pushBlobs( $conn, $itemBatch );
228 if ( is_int( $added ) ) {
229 $pushed += $added;
230 } else {
231 $failed += count( $itemBatch );
234 $this->incrStats( 'inserts', $this->type, count( $items ) );
235 $this->incrStats( 'inserts_actual', $this->type, $pushed );
236 $this->incrStats( 'dupe_inserts', $this->type,
237 count( $items ) - $failed - $pushed );
238 if ( $failed > 0 ) {
239 $err = "Could not insert {$failed} {$this->type} job(s).";
240 wfDebugLog( 'JobQueue', $err );
241 throw new RedisException( $err );
243 } catch ( RedisException $e ) {
244 throw $this->handleErrorAndMakeException( $conn, $e );
249 * @param RedisConnRef $conn
250 * @param array[] $items List of results from JobQueueRedis::getNewJobFields()
251 * @return int Number of jobs inserted (duplicates are ignored)
252 * @throws RedisException
254 protected function pushBlobs( RedisConnRef $conn, array $items ) {
255 $args = [ $this->encodeQueueName() ];
256 // Next args come in 4s ([id, sha1, rtime, blob [, id, sha1, rtime, blob ... ] ] )
257 foreach ( $items as $item ) {
258 $args[] = (string)$item['uuid'];
259 $args[] = (string)$item['sha1'];
260 $args[] = (string)$item['rtimestamp'];
261 $args[] = (string)$this->serialize( $item );
263 static $script =
264 /** @lang Lua */
265 <<<LUA
266 local kUnclaimed, kSha1ById, kIdBySha1, kDelayed, kData, kQwJobs = unpack(KEYS)
267 -- First argument is the queue ID
268 local queueId = ARGV[1]
269 -- Next arguments all come in 4s (one per job)
270 local variadicArgCount = #ARGV - 1
271 if variadicArgCount % 4 ~= 0 then
272 return redis.error_reply('Unmatched arguments')
274 -- Insert each job into this queue as needed
275 local pushed = 0
276 for i = 2,#ARGV,4 do
277 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
278 if sha1 == '' or redis.call('hExists',kIdBySha1,sha1) == 0 then
279 if 1*rtimestamp > 0 then
280 -- Insert into delayed queue (release time as score)
281 redis.call('zAdd',kDelayed,rtimestamp,id)
282 else
283 -- Insert into unclaimed queue
284 redis.call('lPush',kUnclaimed,id)
286 if sha1 ~= '' then
287 redis.call('hSet',kSha1ById,id,sha1)
288 redis.call('hSet',kIdBySha1,sha1,id)
290 redis.call('hSet',kData,id,blob)
291 pushed = pushed + 1
294 -- Mark this queue as having jobs
295 redis.call('sAdd',kQwJobs,queueId)
296 return pushed
297 LUA;
298 return $conn->luaEval( $script,
299 array_merge(
301 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
302 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
303 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
304 $this->getQueueKey( 'z-delayed' ), # KEYS[4]
305 $this->getQueueKey( 'h-data' ), # KEYS[5]
306 $this->getGlobalKey( 's-queuesWithJobs' ), # KEYS[6]
308 $args
310 6 # number of first argument(s) that are keys
315 * @see JobQueue::doPop()
316 * @return RunnableJob|false
317 * @throws JobQueueError
319 protected function doPop() {
320 $job = false;
322 $conn = $this->getConnection();
323 try {
324 do {
325 $blob = $this->popAndAcquireBlob( $conn );
326 if ( !is_string( $blob ) ) {
327 break; // no jobs; nothing to do
330 $this->incrStats( 'pops', $this->type );
331 $item = $this->unserialize( $blob );
332 if ( $item === false ) {
333 wfDebugLog( 'JobQueue', "Could not unserialize {$this->type} job." );
334 continue;
337 // If $item is invalid, the runner loop recycling will cleanup as needed
338 $job = $this->getJobFromFields( $item ); // may be false
339 } while ( !$job ); // job may be false if invalid
340 } catch ( RedisException $e ) {
341 throw $this->handleErrorAndMakeException( $conn, $e );
344 return $job;
348 * @param RedisConnRef $conn
349 * @return array Serialized string or false
350 * @throws RedisException
352 protected function popAndAcquireBlob( RedisConnRef $conn ) {
353 static $script =
354 /** @lang Lua */
355 <<<LUA
356 local kUnclaimed, kSha1ById, kIdBySha1, kClaimed, kAttempts, kData = unpack(KEYS)
357 local rTime = unpack(ARGV)
358 -- Pop an item off the queue
359 local id = redis.call('rPop',kUnclaimed)
360 if not id then
361 return false
363 -- Allow new duplicates of this job
364 local sha1 = redis.call('hGet',kSha1ById,id)
365 if sha1 then redis.call('hDel',kIdBySha1,sha1) end
366 redis.call('hDel',kSha1ById,id)
367 -- Mark the jobs as claimed and return it
368 redis.call('zAdd',kClaimed,rTime,id)
369 redis.call('hIncrBy',kAttempts,id,1)
370 return redis.call('hGet',kData,id)
371 LUA;
372 return $conn->luaEval( $script,
374 $this->getQueueKey( 'l-unclaimed' ), # KEYS[1]
375 $this->getQueueKey( 'h-sha1ById' ), # KEYS[2]
376 $this->getQueueKey( 'h-idBySha1' ), # KEYS[3]
377 $this->getQueueKey( 'z-claimed' ), # KEYS[4]
378 $this->getQueueKey( 'h-attempts' ), # KEYS[5]
379 $this->getQueueKey( 'h-data' ), # KEYS[6]
380 time(), # ARGV[1] (injected to be replication-safe)
382 6 # number of first argument(s) that are keys
387 * @see JobQueue::doAck()
388 * @param RunnableJob $job
389 * @return RunnableJob|bool
390 * @throws UnexpectedValueException
391 * @throws JobQueueError
393 protected function doAck( RunnableJob $job ) {
394 $uuid = $job->getMetadata( 'uuid' );
395 if ( $uuid === null ) {
396 throw new UnexpectedValueException( "Job of type '{$job->getType()}' has no UUID." );
399 $conn = $this->getConnection();
400 try {
401 static $script =
402 /** @lang Lua */
403 <<<LUA
404 local kClaimed, kAttempts, kData = unpack(KEYS)
405 local id = unpack(ARGV)
406 -- Unmark the job as claimed
407 local removed = redis.call('zRem',kClaimed,id)
408 -- Check if the job was recycled
409 if removed == 0 then
410 return 0
412 -- Delete the retry data
413 redis.call('hDel',kAttempts,id)
414 -- Delete the job data itself
415 return redis.call('hDel',kData,id)
416 LUA;
417 $res = $conn->luaEval( $script,
419 $this->getQueueKey( 'z-claimed' ), # KEYS[1]
420 $this->getQueueKey( 'h-attempts' ), # KEYS[2]
421 $this->getQueueKey( 'h-data' ), # KEYS[3]
422 $uuid # ARGV[1]
424 3 # number of first argument(s) that are keys
427 if ( !$res ) {
428 wfDebugLog( 'JobQueue', "Could not acknowledge {$this->type} job $uuid." );
430 return false;
433 $this->incrStats( 'acks', $this->type );
434 } catch ( RedisException $e ) {
435 throw $this->handleErrorAndMakeException( $conn, $e );
438 return true;
442 * @see JobQueue::doDeduplicateRootJob()
443 * @param IJobSpecification $job
444 * @return bool
445 * @throws JobQueueError
447 protected function doDeduplicateRootJob( IJobSpecification $job ) {
448 if ( !$job->hasRootJobParams() ) {
449 throw new LogicException( "Cannot register root job; missing parameters." );
451 $params = $job->getRootJobParams();
453 $key = $this->getRootJobCacheKey( $params['rootJobSignature'], $job->getType() );
455 $conn = $this->getConnection();
456 try {
457 $timestamp = $conn->get( $key ); // last known timestamp of such a root job
458 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
459 return true; // a newer version of this root job was enqueued
462 // Update the timestamp of the last root job started at the location...
463 return $conn->set( $key, $params['rootJobTimestamp'], self::ROOTJOB_TTL ); // 2 weeks
464 } catch ( RedisException $e ) {
465 throw $this->handleErrorAndMakeException( $conn, $e );
470 * @see JobQueue::doIsRootJobOldDuplicate()
471 * @param IJobSpecification $job
472 * @return bool
473 * @throws JobQueueError
475 protected function doIsRootJobOldDuplicate( IJobSpecification $job ) {
476 if ( !$job->hasRootJobParams() ) {
477 return false; // job has no de-duplication info
479 $params = $job->getRootJobParams();
481 $conn = $this->getConnection();
482 try {
483 // Get the last time this root job was enqueued
484 $timestamp = $conn->get( $this->getRootJobCacheKey( $params['rootJobSignature'], $job->getType() ) );
485 } catch ( RedisException $e ) {
486 throw $this->handleErrorAndMakeException( $conn, $e );
489 // Check if a new root job was started at the location after this one's...
490 return ( $timestamp && $timestamp > $params['rootJobTimestamp'] );
494 * @see JobQueue::doDelete()
495 * @return bool
496 * @throws JobQueueError
498 protected function doDelete() {
499 static $props = [ 'l-unclaimed', 'z-claimed', 'z-abandoned',
500 'z-delayed', 'h-idBySha1', 'h-sha1ById', 'h-attempts', 'h-data' ];
502 $conn = $this->getConnection();
503 try {
504 $keys = [];
505 foreach ( $props as $prop ) {
506 $keys[] = $this->getQueueKey( $prop );
509 $ok = ( $conn->del( $keys ) !== false );
510 $conn->sRem( $this->getGlobalKey( 's-queuesWithJobs' ), $this->encodeQueueName() );
512 return $ok;
513 } catch ( RedisException $e ) {
514 throw $this->handleErrorAndMakeException( $conn, $e );
519 * @see JobQueue::getAllQueuedJobs()
520 * @return Iterator<RunnableJob>
521 * @throws JobQueueError
523 public function getAllQueuedJobs() {
524 $conn = $this->getConnection();
525 try {
526 $uids = $conn->lRange( $this->getQueueKey( 'l-unclaimed' ), 0, -1 );
527 } catch ( RedisException $e ) {
528 throw $this->handleErrorAndMakeException( $conn, $e );
531 return $this->getJobIterator( $conn, $uids );
535 * @see JobQueue::getAllDelayedJobs()
536 * @return Iterator<RunnableJob>
537 * @throws JobQueueError
539 public function getAllDelayedJobs() {
540 $conn = $this->getConnection();
541 try {
542 $uids = $conn->zRange( $this->getQueueKey( 'z-delayed' ), 0, -1 );
543 } catch ( RedisException $e ) {
544 throw $this->handleErrorAndMakeException( $conn, $e );
547 return $this->getJobIterator( $conn, $uids );
551 * @see JobQueue::getAllAcquiredJobs()
552 * @return Iterator<RunnableJob>
553 * @throws JobQueueError
555 public function getAllAcquiredJobs() {
556 $conn = $this->getConnection();
557 try {
558 $uids = $conn->zRange( $this->getQueueKey( 'z-claimed' ), 0, -1 );
559 } catch ( RedisException $e ) {
560 throw $this->handleErrorAndMakeException( $conn, $e );
563 return $this->getJobIterator( $conn, $uids );
567 * @see JobQueue::getAllAbandonedJobs()
568 * @return Iterator<RunnableJob>
569 * @throws JobQueueError
571 public function getAllAbandonedJobs() {
572 $conn = $this->getConnection();
573 try {
574 $uids = $conn->zRange( $this->getQueueKey( 'z-abandoned' ), 0, -1 );
575 } catch ( RedisException $e ) {
576 throw $this->handleErrorAndMakeException( $conn, $e );
579 return $this->getJobIterator( $conn, $uids );
583 * @param RedisConnRef $conn
584 * @param array $uids List of job UUIDs
585 * @return MappedIterator<RunnableJob>
587 protected function getJobIterator( RedisConnRef $conn, array $uids ) {
588 return new MappedIterator(
589 $uids,
590 function ( $uid ) use ( $conn ) {
591 return $this->getJobFromUidInternal( $uid, $conn );
593 [ 'accept' => static function ( $job ) {
594 return is_object( $job );
599 public function getCoalesceLocationInternal() {
600 return "RedisServer:" . $this->server;
603 protected function doGetSiblingQueuesWithJobs( array $types ) {
604 return array_keys( array_filter( $this->doGetSiblingQueueSizes( $types ) ) );
607 protected function doGetSiblingQueueSizes( array $types ) {
608 $sizes = []; // (type => size)
609 $types = array_values( $types ); // reindex
610 $conn = $this->getConnection();
611 try {
612 $conn->multi( Redis::PIPELINE );
613 foreach ( $types as $type ) {
614 $conn->lLen( $this->getQueueKey( 'l-unclaimed', $type ) );
616 $res = $conn->exec();
617 if ( is_array( $res ) ) {
618 foreach ( $res as $i => $size ) {
619 $sizes[$types[$i]] = $size;
622 } catch ( RedisException $e ) {
623 throw $this->handleErrorAndMakeException( $conn, $e );
626 return $sizes;
630 * This function should not be called outside JobQueueRedis
632 * @param string $uid
633 * @param RedisConnRef|Redis $conn
634 * @return RunnableJob|false Returns false if the job does not exist
635 * @throws JobQueueError
636 * @throws UnexpectedValueException
638 public function getJobFromUidInternal( $uid, $conn ) {
639 try {
640 $data = $conn->hGet( $this->getQueueKey( 'h-data' ), $uid );
641 if ( $data === false ) {
642 return false; // not found
644 $item = $this->unserialize( $data );
645 if ( !is_array( $item ) ) { // this shouldn't happen
646 throw new UnexpectedValueException( "Could not unserialize job with ID '$uid'." );
649 $params = $item['params'];
650 $params += [ 'namespace' => $item['namespace'], 'title' => $item['title'] ];
651 $job = $this->factoryJob( $item['type'], $params );
652 $job->setMetadata( 'uuid', $item['uuid'] );
653 $job->setMetadata( 'timestamp', $item['timestamp'] );
654 // Add in attempt count for debugging at showJobs.php
655 $job->setMetadata( 'attempts',
656 $conn->hGet( $this->getQueueKey( 'h-attempts' ), $uid ) );
658 return $job;
659 } catch ( RedisException $e ) {
660 throw $this->handleErrorAndMakeException( $conn, $e );
665 * @return array List of (wiki,type) tuples for queues with non-abandoned jobs
666 * @throws JobQueueConnectionError
667 * @throws JobQueueError
669 public function getServerQueuesWithJobs() {
670 $queues = [];
672 $conn = $this->getConnection();
673 try {
674 $set = $conn->sMembers( $this->getGlobalKey( 's-queuesWithJobs' ) );
675 foreach ( $set as $queue ) {
676 $queues[] = $this->decodeQueueName( $queue );
678 } catch ( RedisException $e ) {
679 throw $this->handleErrorAndMakeException( $conn, $e );
682 return $queues;
686 * @param IJobSpecification $job
687 * @return array
689 protected function getNewJobFields( IJobSpecification $job ) {
690 return [
691 // Fields that describe the nature of the job
692 'type' => $job->getType(),
693 'namespace' => $job->getParams()['namespace'] ?? NS_SPECIAL,
694 'title' => $job->getParams()['title'] ?? '',
695 'params' => $job->getParams(),
696 // Some jobs cannot run until a "release timestamp"
697 'rtimestamp' => $job->getReleaseTimestamp() ?: 0,
698 // Additional job metadata
699 'uuid' => $this->idGenerator->newRawUUIDv4(),
700 'sha1' => $job->ignoreDuplicates()
701 ? Wikimedia\base_convert( sha1( serialize( $job->getDeduplicationInfo() ) ), 16, 36, 31 )
702 : '',
703 'timestamp' => time() // UNIX timestamp
708 * @param array $fields
709 * @return RunnableJob|false
711 protected function getJobFromFields( array $fields ) {
712 $params = $fields['params'];
713 $params += [ 'namespace' => $fields['namespace'], 'title' => $fields['title'] ];
715 $job = $this->factoryJob( $fields['type'], $params );
716 $job->setMetadata( 'uuid', $fields['uuid'] );
717 $job->setMetadata( 'timestamp', $fields['timestamp'] );
719 return $job;
723 * @param array $fields
724 * @return string Serialized and possibly compressed version of $fields
726 protected function serialize( array $fields ) {
727 $blob = serialize( $fields );
728 if ( $this->compression === 'gzip'
729 && strlen( $blob ) >= 1024
730 && function_exists( 'gzdeflate' )
732 $object = (object)[ 'blob' => gzdeflate( $blob ), 'enc' => 'gzip' ];
733 $blobz = serialize( $object );
735 return ( strlen( $blobz ) < strlen( $blob ) ) ? $blobz : $blob;
736 } else {
737 return $blob;
742 * @param string $blob
743 * @return array|false Unserialized version of $blob or false
745 protected function unserialize( $blob ) {
746 $fields = unserialize( $blob );
747 if ( is_object( $fields ) ) {
748 if ( $fields->enc === 'gzip' && function_exists( 'gzinflate' ) ) {
749 $fields = unserialize( gzinflate( $fields->blob ) );
750 } else {
751 $fields = false;
755 return is_array( $fields ) ? $fields : false;
759 * Get a connection to the server that handles all sub-queues for this queue
761 * @return RedisConnRef|Redis
762 * @throws JobQueueConnectionError
764 protected function getConnection() {
765 $conn = $this->redisPool->getConnection( $this->server, $this->logger );
766 if ( !$conn ) {
767 throw new JobQueueConnectionError(
768 "Unable to connect to redis server {$this->server}." );
771 return $conn;
775 * @param RedisConnRef $conn
776 * @param RedisException $e
777 * @return JobQueueError
779 protected function handleErrorAndMakeException( RedisConnRef $conn, $e ) {
780 $this->redisPool->handleError( $conn, $e );
781 return new JobQueueError( "Redis server error: {$e->getMessage()}\n" );
785 * @return string JSON
787 private function encodeQueueName() {
788 return json_encode( [ $this->type, $this->domain ] );
792 * @param string $name JSON
793 * @return array (type, wiki)
795 private function decodeQueueName( $name ) {
796 return json_decode( $name );
800 * @param string $name
801 * @return string
803 private function getGlobalKey( $name ) {
804 $parts = [ 'global', 'jobqueue', $name ];
805 foreach ( $parts as $part ) {
806 if ( !preg_match( '/[a-zA-Z0-9_-]+/', $part ) ) {
807 throw new InvalidArgumentException( "Key part characters are out of range." );
811 return implode( ':', $parts );
815 * @param string $prop
816 * @param string|null $type Override this for sibling queues
817 * @return string
819 private function getQueueKey( $prop, $type = null ) {
820 $type = is_string( $type ) ? $type : $this->type;
822 // Use wiki ID for b/c
823 $keyspace = WikiMap::getWikiIdFromDbDomain( $this->domain );
825 $parts = [ $keyspace, 'jobqueue', $type, $prop ];
827 // Parts are typically ASCII, but encode to escape ":"
828 return implode( ':', array_map( 'rawurlencode', $parts ) );