9use InvalidArgumentException;
16use Psr\Log\LoggerInterface;
19use UnexpectedValueException;
80 private const MAX_PUSH_SIZE = 25;
95 parent::__construct( $params );
96 $params[
'redisConfig'][
'serializer'] =
'none';
97 $this->server = $params[
'redisServer'];
98 $this->compression = $params[
'compression'] ??
'none';
100 if ( empty( $params[
'daemonized'] ) ) {
101 throw new InvalidArgumentException(
102 "Non-daemonized mode is no longer supported. Please install the " .
103 "mediawiki/services/jobrunner service and update \$wgJobTypeConf as needed." );
105 $this->logger = LoggerFactory::getInstance(
'redis' );
110 return [
'timestamp',
'fifo' ];
140 return $conn->lLen( $this->getQueueKey(
'l-unclaimed' ) );
141 }
catch ( RedisException $e ) {
154 $conn->multi( Redis::PIPELINE );
155 $conn->zCard( $this->getQueueKey(
'z-claimed' ) );
156 $conn->zCard( $this->getQueueKey(
'z-abandoned' ) );
158 return array_sum( $conn->exec() );
159 }
catch ( RedisException $e ) {
172 return $conn->zCard( $this->getQueueKey(
'z-delayed' ) );
173 }
catch ( RedisException $e ) {
186 return $conn->zCard( $this->getQueueKey(
'z-abandoned' ) );
187 }
catch ( RedisException $e ) {
202 foreach ( $jobs as
$job ) {
204 if ( $item[
'sha1'] !==
'' ) {
205 $items[$item[
'sha1']] = $item;
207 $items[$item[
'uuid']] = $item;
211 if ( $items === [] ) {
218 if ( $flags & self::QOS_ATOMIC ) {
219 $batches = [ $items ];
221 $batches = array_chunk( $items, self::MAX_PUSH_SIZE );
225 foreach ( $batches as $itemBatch ) {
226 $added = $this->
pushBlobs( $conn, $itemBatch );
227 if ( is_int( $added ) ) {
230 $failed += count( $itemBatch );
233 $this->
incrStats(
'inserts', $this->type, count( $items ) );
234 $this->
incrStats(
'inserts_actual', $this->type, $pushed );
235 $this->
incrStats(
'dupe_inserts', $this->type,
236 count( $items ) - $failed - $pushed );
238 $err =
"Could not insert {$failed} {$this->type} job(s).";
240 throw new RedisException( $err );
242 }
catch ( RedisException $e ) {
254 $args = [ $this->encodeQueueName() ];
256 foreach ( $items as $item ) {
257 $args[] = (string)$item[
'uuid'];
258 $args[] = (string)$item[
'sha1'];
259 $args[] = (string)$item[
'rtimestamp'];
260 $args[] = (string)$this->
serialize( $item );
265 local kUnclaimed, kSha1ById, kIdBySha1, kDelayed, kData, kQwJobs = unpack(KEYS)
266 -- First argument is the queue ID
267 local queueId = ARGV[1]
268 -- Next arguments all come in 4s (one per job)
269 local variadicArgCount = #ARGV - 1
270 if variadicArgCount % 4 ~= 0 then
271 return redis.error_reply(
'Unmatched arguments')
273 -- Insert each job into
this queue as needed
276 local id,sha1,rtimestamp,blob = ARGV[i],ARGV[i+1],ARGV[i+2],ARGV[i+3]
277 if sha1 ==
'' or redis.call(
'hExists',kIdBySha1,sha1) == 0 then
278 if 1*rtimestamp > 0 then
279 -- Insert into delayed queue (release time as score)
280 redis.call(
'zAdd',kDelayed,rtimestamp,
id)
282 -- Insert into unclaimed queue
283 redis.call(
'lPush',kUnclaimed,
id)
286 redis.call(
'hSet',kSha1ById,
id,sha1)
287 redis.call(
'hSet',kIdBySha1,sha1,
id)
289 redis.call(
'hSet',kData,
id,blob)
294 -- Mark
this queue as having jobs
295 redis.call(
'sAdd',kQwJobs,queueId)
299 return $conn->
luaEval( $script,
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]
309 6 # number of first argument(s) that are keys
325 if ( !is_string( $blob ) ) {
331 if ( $item ===
false ) {
332 wfDebugLog(
'JobQueue',
"Could not unserialize {$this->type} job." );
339 }
catch ( RedisException $e ) {
355 local kUnclaimed, kSha1ById, kIdBySha1, kClaimed, kAttempts, kData = unpack(KEYS)
356 local rTime = unpack(ARGV)
357 -- Pop an item off the queue
358 local
id = redis.call(
'rPop',kUnclaimed)
362 -- Allow
new duplicates of
this job
363 local sha1 = redis.call(
'hGet',kSha1ById,
id)
364 if sha1 then redis.call(
'hDel',kIdBySha1,sha1) end
365 redis.call(
'hDel',kSha1ById,
id)
366 -- Mark the jobs as claimed and
return it
367 redis.call(
'zAdd',kClaimed,rTime,
id)
368 redis.call(
'hIncrBy',kAttempts,
id,1)
369 return redis.call(
'hGet',kData,
id)
371 return $conn->
luaEval( $script,
373 $this->getQueueKey(
'l-unclaimed' ), # KEYS[1]
374 $this->getQueueKey(
'h-sha1ById' ), # KEYS[2]
375 $this->getQueueKey(
'h-idBySha1' ), # KEYS[3]
376 $this->getQueueKey(
'z-claimed' ), # KEYS[4]
377 $this->getQueueKey(
'h-attempts' ), # KEYS[5]
378 $this->getQueueKey(
'h-data' ), # KEYS[6]
379 time(), # ARGV[1] (injected to be replication-safe)
381 6 # number of first argument(s) that are keys
393 $uuid =
$job->getMetadata(
'uuid' );
394 if ( $uuid ===
null ) {
395 throw new UnexpectedValueException(
"Job of type '{$job->getType()}' has no UUID." );
403 local kClaimed, kAttempts, kData = unpack(KEYS)
404 local
id = unpack(ARGV)
405 -- Unmark the job as claimed
406 local removed = redis.call(
'zRem',kClaimed,
id)
407 -- Check
if the job was recycled
411 -- Delete the retry data
412 redis.call(
'hDel',kAttempts,
id)
413 -- Delete the job data itself
414 return redis.call(
'hDel',kData,
id)
416 $res = $conn->luaEval( $script,
418 $this->getQueueKey(
'z-claimed' ), # KEYS[1]
419 $this->getQueueKey(
'h-attempts' ), # KEYS[2]
420 $this->getQueueKey(
'h-data' ), # KEYS[3]
423 3 # number of first argument(s) that are keys
427 wfDebugLog(
'JobQueue',
"Could not acknowledge {$this->type} job $uuid." );
433 }
catch ( RedisException $e ) {
447 if ( !
$job->hasRootJobParams() ) {
448 throw new LogicException(
"Cannot register root job; missing parameters." );
450 $params =
$job->getRootJobParams();
456 $timestamp = $conn->get( $key );
457 if ( $timestamp && $timestamp >= $params[
'rootJobTimestamp'] ) {
462 return $conn->set( $key, $params[
'rootJobTimestamp'], self::ROOTJOB_TTL );
463 }
catch ( RedisException $e ) {
475 if ( !
$job->hasRootJobParams() ) {
478 $params =
$job->getRootJobParams();
484 }
catch ( RedisException $e ) {
489 return ( $timestamp && $timestamp > $params[
'rootJobTimestamp'] );
498 static $props = [
'l-unclaimed',
'z-claimed',
'z-abandoned',
499 'z-delayed',
'h-idBySha1',
'h-sha1ById',
'h-attempts',
'h-data' ];
504 foreach ( $props as $prop ) {
505 $keys[] = $this->getQueueKey( $prop );
508 $ok = ( $conn->del( $keys ) !== false );
509 $conn->sRem( $this->getGlobalKey(
's-queuesWithJobs' ), $this->encodeQueueName() );
512 }
catch ( RedisException $e ) {
525 $uids = $conn->lRange( $this->getQueueKey(
'l-unclaimed' ), 0, -1 );
526 }
catch ( RedisException $e ) {
541 $uids = $conn->zRange( $this->getQueueKey(
'z-delayed' ), 0, -1 );
542 }
catch ( RedisException $e ) {
557 $uids = $conn->zRange( $this->getQueueKey(
'z-claimed' ), 0, -1 );
558 }
catch ( RedisException $e ) {
573 $uids = $conn->zRange( $this->getQueueKey(
'z-abandoned' ), 0, -1 );
574 }
catch ( RedisException $e ) {
589 function ( $uid ) use ( $conn ) {
592 [
'accept' =>
static function (
$job ) {
593 return is_object(
$job );
611 $types = array_values( $types );
614 $conn->multi( Redis::PIPELINE );
615 foreach ( $types as
$type ) {
616 $conn->lLen( $this->getQueueKey(
'l-unclaimed',
$type ) );
618 $res = $conn->exec();
619 if ( is_array( $res ) ) {
620 foreach ( $res as $i => $size ) {
621 $sizes[$types[$i]] = $size;
624 }
catch ( RedisException $e ) {
642 $data = $conn->hGet( $this->getQueueKey(
'h-data' ), $uid );
643 if ( $data ===
false ) {
647 if ( !is_array( $item ) ) {
648 throw new UnexpectedValueException(
"Could not unserialize job with ID '$uid'." );
651 $params = $item[
'params'];
652 $params += [
'namespace' => $item[
'namespace'],
'title' => $item[
'title'] ];
654 $job->setMetadata(
'uuid', $item[
'uuid'] );
655 $job->setMetadata(
'timestamp', $item[
'timestamp'] );
657 $job->setMetadata(
'attempts',
658 $conn->hGet( $this->getQueueKey(
'h-attempts' ), $uid ) );
661 }
catch ( RedisException $e ) {
676 $set = $conn->sMembers( $this->getGlobalKey(
's-queuesWithJobs' ) );
677 foreach ( $set as $queue ) {
678 $queues[] = $this->decodeQueueName( $queue );
680 }
catch ( RedisException $e ) {
694 'type' =>
$job->getType(),
696 'title' =>
$job->getParams()[
'title'] ??
'',
697 'params' =>
$job->getParams(),
699 'rtimestamp' =>
$job->getReleaseTimestamp() ?: 0,
701 'uuid' => $this->idGenerator->newRawUUIDv4(),
702 'sha1' =>
$job->ignoreDuplicates()
703 ? \Wikimedia\base_convert( sha1(
serialize(
$job->getDeduplicationInfo() ) ), 16, 36, 31 )
705 'timestamp' => time()
714 $params = $fields[
'params'];
715 $params += [
'namespace' => $fields[
'namespace'],
'title' => $fields[
'title'] ];
718 $job->setMetadata(
'uuid', $fields[
'uuid'] );
719 $job->setMetadata(
'timestamp', $fields[
'timestamp'] );
730 if ( $this->compression ===
'gzip'
731 && strlen( $blob ) >= 1024
732 && function_exists(
'gzdeflate' )
734 $object = (object)[
'blob' => gzdeflate( $blob ),
'enc' =>
'gzip' ];
737 return ( strlen( $blobz ) < strlen( $blob ) ) ? $blobz : $blob;
749 if ( is_object( $fields ) ) {
750 if ( $fields->enc ===
'gzip' && function_exists(
'gzinflate' ) ) {
751 $fields =
unserialize( gzinflate( $fields->blob ) );
757 return is_array( $fields ) ? $fields :
false;
767 $conn = $this->redisPool->getConnection( $this->server, $this->logger );
770 "Unable to connect to redis server {$this->server}." );
782 $this->redisPool->handleError( $conn, $e );
783 return new JobQueueError(
"Redis server error: {$e->getMessage()}\n" );
789 private function encodeQueueName() {
790 return json_encode( [ $this->type, $this->domain ] );
797 private function decodeQueueName( $name ) {
798 return json_decode( $name );
805 private function getGlobalKey( $name ) {
806 $parts = [
'global',
'jobqueue', $name ];
807 foreach ( $parts as $part ) {
808 if ( !preg_match(
'/[a-zA-Z0-9_-]+/', $part ) ) {
809 throw new InvalidArgumentException(
"Key part characters are out of range." );
813 return implode(
':', $parts );
821 private function getQueueKey( $prop,
$type =
null ) {
825 $keyspace = WikiMap::getWikiIdFromDbDomain( $this->domain );
827 $parts = [ $keyspace,
'jobqueue',
$type, $prop ];
830 return implode(
':', array_map(
'rawurlencode', $parts ) );
835class_alias( JobQueueRedis::class,
'JobQueueRedis' );
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Convenience class for generating iterators from iterators.
if(count( $args)< 1) $job