28use Wikimedia\ScopedCallback;
37 private const CACHE_TTL_SHORT = 30;
38 private const MAX_AGE_PRUNE = 604800;
39 private const MAX_JOB_RANDOM = 2147483647;
40 private const MAX_OFFSET = 255;
60 parent::__construct( $params );
62 if ( isset( $params[
'server'] ) ) {
63 $this->server = $params[
'server'];
64 } elseif ( isset( $params[
'cluster'] ) && is_string( $params[
'cluster'] ) ) {
65 $this->cluster = $params[
'cluster'];
70 return [
'random',
'timestamp',
'fifo' ];
84 $scope = $this->getScopedNoTrxFlag(
$dbr );
87 $found = (bool)
$dbr->newSelectQueryBuilder()
90 ->where( [
'job_cmd' => $this->type,
'job_token' =>
'' ] )
91 ->caller( __METHOD__ )->fetchField();
104 $key = $this->getCacheKey(
'size' );
106 $size = $this->wanCache->get( $key );
107 if ( is_int( $size ) ) {
113 $scope = $this->getScopedNoTrxFlag(
$dbr );
115 $size =
$dbr->newSelectQueryBuilder()
117 ->where( [
'job_cmd' => $this->type,
'job_token' =>
'' ] )
118 ->caller( __METHOD__ )->fetchRowCount();
122 $this->wanCache->set( $key, $size, self::CACHE_TTL_SHORT );
132 if ( $this->claimTTL <= 0 ) {
136 $key = $this->getCacheKey(
'acquiredcount' );
138 $count = $this->wanCache->get( $key );
139 if ( is_int( $count ) ) {
145 $scope = $this->getScopedNoTrxFlag(
$dbr );
147 $count =
$dbr->newSelectQueryBuilder()
149 ->where( [
'job_cmd' => $this->type,
"job_token != {$dbr->addQuotes( '' )}" ] )
150 ->caller( __METHOD__ )->fetchRowCount();
154 $this->wanCache->set( $key, $count, self::CACHE_TTL_SHORT );
165 if ( $this->claimTTL <= 0 ) {
169 $key = $this->getCacheKey(
'abandonedcount' );
171 $count = $this->wanCache->get( $key );
172 if ( is_int( $count ) ) {
178 $scope = $this->getScopedNoTrxFlag(
$dbr );
180 $count =
$dbr->newSelectQueryBuilder()
184 'job_cmd' => $this->type,
185 "job_token != {$dbr->addQuotes( '' )}",
186 $dbr->buildComparison(
'>=', [
'job_attempts' => $this->maxTries ] ),
189 ->caller( __METHOD__ )->fetchRowCount();
194 $this->wanCache->set( $key, $count, self::CACHE_TTL_SHORT );
209 $scope = $this->getScopedNoTrxFlag( $dbw );
220 $dbw->onTransactionPreCommitOrIdle(
221 function (
IDatabase $dbw ) use ( $jobs, $flags, $fname ) {
240 if ( $jobs === [] ) {
246 foreach ( $jobs as
$job ) {
248 if (
$job->ignoreDuplicates() ) {
249 $rowSet[$row[
'job_sha1']] = $row;
255 if ( $flags & self::QOS_ATOMIC ) {
260 if ( count( $rowSet ) ) {
262 ->select(
'job_sha1' )
267 'job_sha1' => array_map(
'strval', array_keys( $rowSet ) ),
271 ->caller( $method )->fetchResultSet();
272 foreach (
$res as $row ) {
273 wfDebug(
"Job with hash '{$row->job_sha1}' is a duplicate." );
274 unset( $rowSet[$row->job_sha1] );
278 $rows = array_merge( $rowList, array_values( $rowSet ) );
280 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
281 $dbw->
insert(
'job', $rowBatch, $method );
283 $this->
incrStats(
'inserts', $this->type, count( $rows ) );
284 $this->
incrStats(
'dupe_inserts', $this->type,
285 count( $rowSet ) + count( $rowList ) - count( $rows )
290 if ( $flags & self::QOS_ATOMIC ) {
302 $scope = $this->getScopedNoTrxFlag( $dbw );
309 if ( in_array( $this->order, [
'fifo',
'timestamp' ] ) ) {
312 $rand = mt_rand( 0, self::MAX_JOB_RANDOM );
313 $gte = (bool)mt_rand( 0, 1 );
327 if ( !
$job || mt_rand( 0, 9 ) == 0 ) {
350 $scope = $this->getScopedNoTrxFlag( $dbw );
352 $tinyQueue = $this->wanCache->get( $this->getCacheKey(
'small' ) );
354 $invertedDirection =
false;
363 $row = $dbw->newSelectQueryBuilder()
364 ->select( self::selectFields() )
368 'job_cmd' => $this->type,
370 $dbw->buildComparison( $gte ?
'>=' :
'<=', [
'job_random' => $rand ] )
375 $gte ? SelectQueryBuilder::SORT_ASC : SelectQueryBuilder::SORT_DESC
377 ->caller( __METHOD__ )->fetchRow();
378 if ( !$row && !$invertedDirection ) {
380 $invertedDirection =
true;
387 $row = $dbw->newSelectQueryBuilder()
388 ->select( self::selectFields() )
392 'job_cmd' => $this->type,
396 ->offset( mt_rand( 0, self::MAX_OFFSET ) )
397 ->caller( __METHOD__ )->fetchRow();
400 $this->wanCache->set( $this->getCacheKey(
'small' ), 1, 30 );
411 'job_token' => $uuid,
412 'job_token_timestamp' => $dbw->timestamp(),
413 'job_attempts = job_attempts+1' ],
414 [
'job_cmd' =>
$this->type,
'job_id' => $row->job_id,
'job_token' =>
'' ],
419 if ( !$dbw->affectedRows() ) {
436 $scope = $this->getScopedNoTrxFlag( $dbw );
440 if ( $dbw->getType() ===
'mysql' ) {
445 $dbw->query(
"UPDATE {$dbw->tableName( 'job' )} " .
447 "job_token = {$dbw->addQuotes( $uuid ) }, " .
448 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
449 "job_attempts = job_attempts+1 " .
451 "job_cmd = {$dbw->addQuotes( $this->type )} " .
452 "AND job_token = {$dbw->addQuotes( '' )} " .
453 ") ORDER BY job_id ASC LIMIT 1",
459 $qb = $dbw->newSelectQueryBuilder()
462 ->where( [
'job_cmd' => $this->type,
'job_token' =>
'' ] )
463 ->orderBy(
'job_id', SelectQueryBuilder::SORT_ASC )
468 'job_token' => $uuid,
469 'job_token_timestamp' => $dbw->timestamp(),
470 'job_attempts = job_attempts+1' ],
471 [
'job_id = (' . $qb->getSQL() .
')'
477 if ( !$dbw->affectedRows() ) {
482 $row = $dbw->newSelectQueryBuilder()
483 ->select( self::selectFields() )
485 ->where( [
'job_cmd' => $this->type,
'job_token' => $uuid ] )
486 ->caller( __METHOD__ )->fetchRow();
488 wfDebug(
"Row deleted as duplicate by another process." );
501 $id =
$job->getMetadata(
'id' );
502 if ( $id ===
null ) {
503 throw new MWException(
"Job of type '{$job->getType()}' has no ID." );
508 $scope = $this->getScopedNoTrxFlag( $dbw );
513 [
'job_cmd' => $this->type,
'job_id' => $id ],
537 $scope = $this->getScopedNoTrxFlag( $dbw );
538 $dbw->onTransactionCommitOrIdle(
539 function () use (
$job ) {
540 parent::doDeduplicateRootJob(
$job );
555 $scope = $this->getScopedNoTrxFlag( $dbw );
557 $dbw->delete(
'job', [
'job_cmd' => $this->type ], __METHOD__ );
570 if ( $this->server ) {
574 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
575 $lbFactory->waitForReplication( [
576 'domain' => $this->domain,
577 'cluster' => is_string( $this->cluster ) ? $this->cluster : false
585 foreach ( [
'size',
'acquiredcount' ] as
$type ) {
586 $this->wanCache->delete( $this->getCacheKey(
$type ) );
614 "job_attempts >= " . intval( $this->maxTries )
625 $scope = $this->getScopedNoTrxFlag(
$dbr );
626 $qb =
$dbr->newSelectQueryBuilder()
627 ->select( self::selectFields() )
632 $qb->caller( __METHOD__ )->fetchResultSet(),
643 if ( $this->server ) {
647 return is_string( $this->cluster )
648 ?
"DBCluster:{$this->cluster}:{$this->domain}"
649 :
"LBFactory:{$this->domain}";
655 $scope = $this->getScopedNoTrxFlag(
$dbr );
660 $res =
$dbr->newSelectQueryBuilder()
661 ->select(
'job_cmd' )
664 ->where( [
'job_cmd' => $types ] )
665 ->caller( __METHOD__ )->fetchResultSet();
668 foreach (
$res as $row ) {
669 $types[] = $row->job_cmd;
678 $scope = $this->getScopedNoTrxFlag(
$dbr );
680 $res =
$dbr->newSelectQueryBuilder()
681 ->select( [
'job_cmd',
'count' =>
'COUNT(*)' ] )
683 ->where( [
'job_cmd' => $types ] )
684 ->groupBy(
'job_cmd' )
685 ->caller( __METHOD__ )->fetchResultSet();
688 foreach (
$res as $row ) {
689 $sizes[$row->job_cmd] = (int)$row->count;
705 $scope = $this->getScopedNoTrxFlag( $dbw );
708 if ( !$dbw->lock(
"jobqueue-recycle-{$this->type}", __METHOD__, 1 ) ) {
713 if ( $this->claimTTL > 0 ) {
714 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL );
718 $res = $dbw->newSelectQueryBuilder()
723 'job_cmd' => $this->type,
724 "job_token != {$dbw->addQuotes( '' )}",
725 $dbw->buildComparison(
'<', [
'job_token_timestamp' => $claimCutoff ] ),
726 $dbw->buildComparison(
'<', [
'job_attempts' => $this->maxTries ] ),
729 ->caller( __METHOD__ )->fetchResultSet();
731 static function ( $o ) {
733 }, iterator_to_array(
$res )
735 if ( count( $ids ) ) {
742 'job_token_timestamp' => $dbw->timestamp( $now )
744 [
'job_id' => $ids,
"job_token != {$dbw->addQuotes( '' )}" ],
747 $affected = $dbw->affectedRows();
749 $this->
incrStats(
'recycles', $this->type, $affected );
754 $pruneCutoff = $dbw->timestamp( $now - self::MAX_AGE_PRUNE );
755 $qb = $dbw->newSelectQueryBuilder()
760 'job_cmd' => $this->type,
761 "job_token != {$dbw->addQuotes( '' )}",
762 $dbw->buildComparison(
'<', [
'job_token_timestamp' => $pruneCutoff ] )
765 if ( $this->claimTTL > 0 ) {
766 $qb->andWhere(
"job_attempts >= {$dbw->addQuotes( $this->maxTries )}" );
770 $res = $qb->caller( __METHOD__ )->fetchResultSet();
772 static function ( $o ) {
774 }, iterator_to_array(
$res )
776 if ( count( $ids ) ) {
777 $dbw->delete(
'job', [
'job_id' => $ids ], __METHOD__ );
778 $affected = $dbw->affectedRows();
780 $this->
incrStats(
'abandons', $this->type, $affected );
783 $dbw->unlock(
"jobqueue-recycle-{$this->type}", __METHOD__ );
799 'job_cmd' =>
$job->getType(),
801 'job_title' =>
$job->getParams()[
'title'] ??
'',
802 'job_params' => self::makeBlob(
$job->getParams() ),
805 'job_sha1' => Wikimedia\base_convert(
806 sha1( serialize(
$job->getDeduplicationInfo() ) ),
809 'job_random' => mt_rand( 0, self::MAX_JOB_RANDOM )
842 protected function getDB( $index ) {
843 if ( $this->server ) {
844 if ( $this->conn instanceof
IDatabase ) {
846 } elseif ( $this->conn instanceof
DBError ) {
851 $this->conn = MediaWikiServices::getInstance()->getDatabaseFactory()->create(
852 $this->server[
'type'],
862 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
863 $lb = is_string( $this->cluster )
864 ? $lbFactory->getExternalLB( $this->cluster )
865 : $lbFactory->getMainLB( $this->domain );
867 if ( $lb->getServerType( $lb->getWriterIndex() ) !==
'sqlite' ) {
870 $flags = $lb::CONN_TRX_AUTOCOMMIT;
876 return $lb->getMaintenanceConnectionRef( $index, [], $this->domain, $flags );
884 private function getScopedNoTrxFlag(
IDatabase $db ) {
888 return new ScopedCallback(
static function () use ( $db, $autoTrx ) {
899 private function getCacheKey( $property ) {
900 $cluster = is_string( $this->cluster ) ? $this->cluster :
'main';
902 return $this->wanCache->makeGlobalKey(
916 if ( $params !==
false ) {
917 return serialize( $params );
928 $params = ( (string)$row->job_params !==
'' ) ? unserialize( $row->job_params ) : [];
929 if ( !is_array( $params ) ) {
930 throw new UnexpectedValueException(
931 "Could not unserialize job with ID '{$row->job_id}'." );
934 $params += [
'namespace' => $row->job_namespace,
'title' => $row->job_title ];
936 $job->setMetadata(
'id', $row->job_id );
937 $job->setMetadata(
'timestamp', $row->job_timestamp );
947 return new JobQueueError( get_class( $e ) .
": " . $e->getMessage() );
966 'job_token_timestamp',
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Class to handle job queues stored in the DB.
claimOldest( $uuid)
Reserve a row with a single UPDATE without holding row locks over RTTs...
supportedOrders()
Get the allowed queue orders for configuration validation.
doGetSiblingQueueSizes(array $types)
insertFields(IJobSpecification $job, IDatabase $db)
__construct(array $params)
Additional parameters include:
getDBException(DBError $e)
doBatchPush(array $jobs, $flags)
static makeBlob( $params)
claimRandom( $uuid, $rand, $gte)
Reserve a row with a single UPDATE without holding row locks over RTTs...
doGetSiblingQueuesWithJobs(array $types)
recycleAndDeleteStaleJobs()
Recycle or destroy any jobs that have been claimed for too long.
doBatchPushInternal(IDatabase $dbw, array $jobs, $flags, $method)
This function should not be called outside of JobQueueDB.
optimalOrder()
Get the default queue order to use if configuration does not specify one.
string null $cluster
Name of an external DB cluster or null for the local DB cluster.
IMaintainableDatabase DBError null $conn
getCoalesceLocationInternal()
Do not use this function outside of JobQueue/JobQueueGroup.
doDeduplicateRootJob(IJobSpecification $job)
static selectFields()
Return the list of job fields that should be selected.
getJobIterator(array $conds)
array null $server
Server configuration array.
Class to handle enqueueing and running of background jobs.
incrStats( $key, $type, $delta=1)
Call StatsdDataFactoryInterface::updateCount() for the queue overall and for the queue type.
factoryJob( $command, $params)
Convenience class for generating iterators from iterators.
Interface for serializable objects that describe a job queue task.
Job that has a run() method and metadata accessors for JobQueue::pop() and JobQueue::ack()
Advanced database interface for IDatabase handles that include maintenance methods.
if(count( $args)< 1) $job