3 * Database-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
22 use Wikimedia\Rdbms\IDatabase
;
23 use Wikimedia\Rdbms\Database
;
24 use Wikimedia\Rdbms\DBConnectionError
;
25 use Wikimedia\Rdbms\DBError
;
26 use MediaWiki\MediaWikiServices
;
27 use Wikimedia\ScopedCallback
;
30 * Class to handle job queues stored in the DB
35 class JobQueueDB
extends JobQueue
{
36 const CACHE_TTL_SHORT
= 30; // integer; seconds to cache info without re-validating
37 const MAX_AGE_PRUNE
= 604800; // integer; seconds a job can live once claimed
38 const MAX_JOB_RANDOM
= 2147483647; // integer; 2^31 - 1, used for job_random
39 const MAX_OFFSET
= 255; // integer; maximum number of rows to skip
41 /** @var WANObjectCache */
43 /** @var IDatabase|DBError|null */
46 /** @var array|null Server configuration array */
48 /** @var string|null Name of an external DB cluster or null for the local DB cluster */
52 * Additional parameters include:
53 * - server : Server configuration array for Database::factory. Overrides "cluster".
54 * - cluster : The name of an external cluster registered via LBFactory.
55 * If not specified, the primary DB cluster for the wiki will be used.
56 * This can be overridden with a custom cluster so that DB handles will
57 * be retrieved via LBFactory::getExternalLB() and getConnection().
58 * - wanCache : An instance of WANObjectCache to use for caching.
59 * @param array $params
61 protected function __construct( array $params ) {
62 parent
::__construct( $params );
64 if ( isset( $params['server'] ) ) {
65 $this->server
= $params['server'];
66 } elseif ( isset( $params['cluster'] ) && is_string( $params['cluster'] ) ) {
67 $this->cluster
= $params['cluster'];
70 $this->cache
= $params['wanCache'] ?? WANObjectCache
::newEmpty();
73 protected function supportedOrders() {
74 return [ 'random', 'timestamp', 'fifo' ];
77 protected function optimalOrder() {
82 * @see JobQueue::doIsEmpty()
85 protected function doIsEmpty() {
86 $dbr = $this->getReplicaDB();
87 /** @noinspection PhpUnusedLocalVariableInspection */
88 $scope = $this->getScopedNoTrxFlag( $dbr );
90 $found = $dbr->selectField( // unclaimed job
91 'job', '1', [ 'job_cmd' => $this->type
, 'job_token' => '' ], __METHOD__
93 } catch ( DBError
$e ) {
94 throw $this->getDBException( $e );
101 * @see JobQueue::doGetSize()
104 protected function doGetSize() {
105 $key = $this->getCacheKey( 'size' );
107 $size = $this->cache
->get( $key );
108 if ( is_int( $size ) ) {
112 $dbr = $this->getReplicaDB();
113 /** @noinspection PhpUnusedLocalVariableInspection */
114 $scope = $this->getScopedNoTrxFlag( $dbr );
116 $size = (int)$dbr->selectField( 'job', 'COUNT(*)',
117 [ 'job_cmd' => $this->type
, 'job_token' => '' ],
120 } catch ( DBError
$e ) {
121 throw $this->getDBException( $e );
123 $this->cache
->set( $key, $size, self
::CACHE_TTL_SHORT
);
129 * @see JobQueue::doGetAcquiredCount()
132 protected function doGetAcquiredCount() {
133 if ( $this->claimTTL
<= 0 ) {
134 return 0; // no acknowledgements
137 $key = $this->getCacheKey( 'acquiredcount' );
139 $count = $this->cache
->get( $key );
140 if ( is_int( $count ) ) {
144 $dbr = $this->getReplicaDB();
145 /** @noinspection PhpUnusedLocalVariableInspection */
146 $scope = $this->getScopedNoTrxFlag( $dbr );
148 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
149 [ 'job_cmd' => $this->type
, "job_token != {$dbr->addQuotes( '' )}" ],
152 } catch ( DBError
$e ) {
153 throw $this->getDBException( $e );
155 $this->cache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
161 * @see JobQueue::doGetAbandonedCount()
163 * @throws MWException
165 protected function doGetAbandonedCount() {
166 if ( $this->claimTTL
<= 0 ) {
167 return 0; // no acknowledgements
170 $key = $this->getCacheKey( 'abandonedcount' );
172 $count = $this->cache
->get( $key );
173 if ( is_int( $count ) ) {
177 $dbr = $this->getReplicaDB();
178 /** @noinspection PhpUnusedLocalVariableInspection */
179 $scope = $this->getScopedNoTrxFlag( $dbr );
181 $count = (int)$dbr->selectField( 'job', 'COUNT(*)',
183 'job_cmd' => $this->type
,
184 "job_token != {$dbr->addQuotes( '' )}",
185 "job_attempts >= " . $dbr->addQuotes( $this->maxTries
)
189 } catch ( DBError
$e ) {
190 throw $this->getDBException( $e );
193 $this->cache
->set( $key, $count, self
::CACHE_TTL_SHORT
);
199 * @see JobQueue::doBatchPush()
200 * @param IJobSpecification[] $jobs
202 * @throws DBError|Exception
205 protected function doBatchPush( array $jobs, $flags ) {
206 $dbw = $this->getMasterDB();
207 /** @noinspection PhpUnusedLocalVariableInspection */
208 $scope = $this->getScopedNoTrxFlag( $dbw );
209 // In general, there will be two cases here:
210 // a) sqlite; DB connection is probably a regular round-aware handle.
211 // If the connection is busy with a transaction, then defer the job writes
212 // until right before the main round commit step. Any errors that bubble
213 // up will rollback the main commit round.
214 // b) mysql/postgres; DB connection is generally a separate CONN_TRX_AUTOCOMMIT handle.
215 // No transaction is active nor will be started by writes, so enqueue the jobs
216 // now so that any errors will show up immediately as the interface expects. Any
217 // errors that bubble up will rollback the main commit round.
219 $dbw->onTransactionPreCommitOrIdle(
220 function ( IDatabase
$dbw ) use ( $jobs, $flags, $fname ) {
221 $this->doBatchPushInternal( $dbw, $jobs, $flags, $fname );
228 * This function should *not* be called outside of JobQueueDB
230 * @suppress SecurityCheck-SQLInjection Bug in phan-taint-check handling bulk inserts
231 * @param IDatabase $dbw
232 * @param IJobSpecification[] $jobs
234 * @param string $method
238 public function doBatchPushInternal( IDatabase
$dbw, array $jobs, $flags, $method ) {
239 if ( $jobs === [] ) {
243 $rowSet = []; // (sha1 => job) map for jobs that are de-duplicated
244 $rowList = []; // list of jobs for jobs that are not de-duplicated
245 foreach ( $jobs as $job ) {
246 $row = $this->insertFields( $job, $dbw );
247 if ( $job->ignoreDuplicates() ) {
248 $rowSet[$row['job_sha1']] = $row;
254 if ( $flags & self
::QOS_ATOMIC
) {
255 $dbw->startAtomic( $method ); // wrap all the job additions in one transaction
258 // Strip out any duplicate jobs that are already in the queue...
259 if ( count( $rowSet ) ) {
260 $res = $dbw->select( 'job', 'job_sha1',
262 // No job_type condition since it's part of the job_sha1 hash
263 'job_sha1' => array_keys( $rowSet ),
264 'job_token' => '' // unclaimed
268 foreach ( $res as $row ) {
269 wfDebug( "Job with hash '{$row->job_sha1}' is a duplicate.\n" );
270 unset( $rowSet[$row->job_sha1
] ); // already enqueued
273 // Build the full list of job rows to insert
274 $rows = array_merge( $rowList, array_values( $rowSet ) );
275 // Insert the job rows in chunks to avoid replica DB lag...
276 foreach ( array_chunk( $rows, 50 ) as $rowBatch ) {
277 $dbw->insert( 'job', $rowBatch, $method );
279 $this->incrStats( 'inserts', $this->type
, count( $rows ) );
280 $this->incrStats( 'dupe_inserts', $this->type
,
281 count( $rowSet ) +
count( $rowList ) - count( $rows )
283 } catch ( DBError
$e ) {
284 throw $this->getDBException( $e );
286 if ( $flags & self
::QOS_ATOMIC
) {
287 $dbw->endAtomic( $method );
292 * @see JobQueue::doPop()
293 * @return RunnableJob|bool
295 protected function doPop() {
296 $dbw = $this->getMasterDB();
297 /** @noinspection PhpUnusedLocalVariableInspection */
298 $scope = $this->getScopedNoTrxFlag( $dbw );
300 $job = false; // job popped off
302 $uuid = wfRandomString( 32 ); // pop attempt
303 do { // retry when our row is invalid or deleted as a duplicate
304 // Try to reserve a row in the DB...
305 if ( in_array( $this->order
, [ 'fifo', 'timestamp' ] ) ) {
306 $row = $this->claimOldest( $uuid );
307 } else { // random first
308 $rand = mt_rand( 0, self
::MAX_JOB_RANDOM
); // encourage concurrent UPDATEs
309 $gte = (bool)mt_rand( 0, 1 ); // find rows with rand before/after $rand
310 $row = $this->claimRandom( $uuid, $rand, $gte );
312 // Check if we found a row to reserve...
314 break; // nothing to do
316 $this->incrStats( 'pops', $this->type
);
318 // Get the job object from the row...
319 $job = $this->jobFromRow( $row );
323 if ( !$job ||
mt_rand( 0, 9 ) == 0 ) {
324 // Handled jobs that need to be recycled/deleted;
325 // any recycled jobs will be picked up next attempt
326 $this->recycleAndDeleteStaleJobs();
328 } catch ( DBError
$e ) {
329 throw $this->getDBException( $e );
336 * Reserve a row with a single UPDATE without holding row locks over RTTs...
338 * @param string $uuid 32 char hex string
339 * @param int $rand Random unsigned integer (31 bits)
340 * @param bool $gte Search for job_random >= $random (otherwise job_random <= $random)
341 * @return stdClass|bool Row|false
343 protected function claimRandom( $uuid, $rand, $gte ) {
344 $dbw = $this->getMasterDB();
345 /** @noinspection PhpUnusedLocalVariableInspection */
346 $scope = $this->getScopedNoTrxFlag( $dbw );
347 // Check cache to see if the queue has <= OFFSET items
348 $tinyQueue = $this->cache
->get( $this->getCacheKey( 'small' ) );
350 $invertedDirection = false; // whether one job_random direction was already scanned
351 // This uses a replication safe method for acquiring jobs. One could use UPDATE+LIMIT
352 // instead, but that either uses ORDER BY (in which case it deadlocks in MySQL) or is
353 // not replication safe. Due to https://bugs.mysql.com/bug.php?id=6980, subqueries cannot
354 // be used here with MySQL.
356 if ( $tinyQueue ) { // queue has <= MAX_OFFSET rows
357 // For small queues, using OFFSET will overshoot and return no rows more often.
358 // Instead, this uses job_random to pick a row (possibly checking both directions).
359 $ineq = $gte ?
'>=' : '<=';
360 $dir = $gte ?
'ASC' : 'DESC';
361 $row = $dbw->selectRow( 'job', self
::selectFields(), // find a random job
363 'job_cmd' => $this->type
,
364 'job_token' => '', // unclaimed
365 "job_random {$ineq} {$dbw->addQuotes( $rand )}" ],
367 [ 'ORDER BY' => "job_random {$dir}" ]
369 if ( !$row && !$invertedDirection ) {
371 $invertedDirection = true;
372 continue; // try the other direction
374 } else { // table *may* have >= MAX_OFFSET rows
375 // T44614: "ORDER BY job_random" with a job_random inequality causes high CPU
376 // in MySQL if there are many rows for some reason. This uses a small OFFSET
377 // instead of job_random for reducing excess claim retries.
378 $row = $dbw->selectRow( 'job', self
::selectFields(), // find a random job
380 'job_cmd' => $this->type
,
381 'job_token' => '', // unclaimed
384 [ 'OFFSET' => mt_rand( 0, self
::MAX_OFFSET
) ]
387 $tinyQueue = true; // we know the queue must have <= MAX_OFFSET rows
388 $this->cache
->set( $this->getCacheKey( 'small' ), 1, 30 );
389 continue; // use job_random
393 if ( $row ) { // claim the job
394 $dbw->update( 'job', // update by PK
396 'job_token' => $uuid,
397 'job_token_timestamp' => $dbw->timestamp(),
398 'job_attempts = job_attempts+1' ],
399 [ 'job_cmd' => $this->type
, 'job_id' => $row->job_id
, 'job_token' => '' ],
402 // This might get raced out by another runner when claiming the previously
403 // selected row. The use of job_random should minimize this problem, however.
404 if ( !$dbw->affectedRows() ) {
405 $row = false; // raced out
408 break; // nothing to do
416 * Reserve a row with a single UPDATE without holding row locks over RTTs...
418 * @param string $uuid 32 char hex string
419 * @return stdClass|bool Row|false
421 protected function claimOldest( $uuid ) {
422 $dbw = $this->getMasterDB();
423 /** @noinspection PhpUnusedLocalVariableInspection */
424 $scope = $this->getScopedNoTrxFlag( $dbw );
426 $row = false; // the row acquired
428 if ( $dbw->getType() === 'mysql' ) {
429 // Per https://bugs.mysql.com/bug.php?id=6980, we can't use subqueries on the
430 // same table being changed in an UPDATE query in MySQL (gives Error: 1093).
431 // Oracle and Postgre have no such limitation. However, MySQL offers an
432 // alternative here by supporting ORDER BY + LIMIT for UPDATE queries.
433 $dbw->query( "UPDATE {$dbw->tableName( 'job' )} " .
435 "job_token = {$dbw->addQuotes( $uuid ) }, " .
436 "job_token_timestamp = {$dbw->addQuotes( $dbw->timestamp() )}, " .
437 "job_attempts = job_attempts+1 " .
439 "job_cmd = {$dbw->addQuotes( $this->type )} " .
440 "AND job_token = {$dbw->addQuotes( '' )} " .
441 ") ORDER BY job_id ASC LIMIT 1",
445 // Use a subquery to find the job, within an UPDATE to claim it.
446 // This uses as much of the DB wrapper functions as possible.
449 'job_token' => $uuid,
450 'job_token_timestamp' => $dbw->timestamp(),
451 'job_attempts = job_attempts+1' ],
453 $dbw->selectSQLText( 'job', 'job_id',
454 [ 'job_cmd' => $this->type
, 'job_token' => '' ],
456 [ 'ORDER BY' => 'job_id ASC', 'LIMIT' => 1 ] ) .
462 // Fetch any row that we just reserved...
463 if ( $dbw->affectedRows() ) {
464 $row = $dbw->selectRow( 'job', self
::selectFields(),
465 [ 'job_cmd' => $this->type
, 'job_token' => $uuid ], __METHOD__
467 if ( !$row ) { // raced out by duplicate job removal
468 wfDebug( "Row deleted as duplicate by another process.\n" );
471 break; // nothing to do
479 * @see JobQueue::doAck()
480 * @param RunnableJob $job
481 * @throws MWException
483 protected function doAck( RunnableJob
$job ) {
484 $id = $job->getMetadata( 'id' );
485 if ( $id === null ) {
486 throw new MWException( "Job of type '{$job->getType()}' has no ID." );
489 $dbw = $this->getMasterDB();
490 /** @noinspection PhpUnusedLocalVariableInspection */
491 $scope = $this->getScopedNoTrxFlag( $dbw );
493 // Delete a row with a single DELETE without holding row locks over RTTs...
496 [ 'job_cmd' => $this->type
, 'job_id' => $id ],
500 $this->incrStats( 'acks', $this->type
);
501 } catch ( DBError
$e ) {
502 throw $this->getDBException( $e );
507 * @see JobQueue::doDeduplicateRootJob()
508 * @param IJobSpecification $job
509 * @throws MWException
512 protected function doDeduplicateRootJob( IJobSpecification
$job ) {
513 $params = $job->getParams();
514 if ( !isset( $params['rootJobSignature'] ) ) {
515 throw new MWException( "Cannot register root job; missing 'rootJobSignature'." );
516 } elseif ( !isset( $params['rootJobTimestamp'] ) ) {
517 throw new MWException( "Cannot register root job; missing 'rootJobTimestamp'." );
519 $key = $this->getRootJobCacheKey( $params['rootJobSignature'] );
520 // Callers should call JobQueueGroup::push() before this method so that if the insert
521 // fails, the de-duplication registration will be aborted. Since the insert is
522 // deferred till "transaction idle", do the same here, so that the ordering is
523 // maintained. Having only the de-duplication registration succeed would cause
524 // jobs to become no-ops without any actual jobs that made them redundant.
525 $dbw = $this->getMasterDB();
526 /** @noinspection PhpUnusedLocalVariableInspection */
527 $scope = $this->getScopedNoTrxFlag( $dbw );
529 $cache = $this->dupCache
;
530 $dbw->onTransactionCommitOrIdle(
531 function () use ( $cache, $params, $key ) {
532 $timestamp = $cache->get( $key ); // current last timestamp of this job
533 if ( $timestamp && $timestamp >= $params['rootJobTimestamp'] ) {
534 return true; // a newer version of this root job was enqueued
537 // Update the timestamp of the last root job started at the location...
538 return $cache->set( $key, $params['rootJobTimestamp'], JobQueueDB
::ROOTJOB_TTL
);
547 * @see JobQueue::doDelete()
550 protected function doDelete() {
551 $dbw = $this->getMasterDB();
552 /** @noinspection PhpUnusedLocalVariableInspection */
553 $scope = $this->getScopedNoTrxFlag( $dbw );
555 $dbw->delete( 'job', [ 'job_cmd' => $this->type
] );
556 } catch ( DBError
$e ) {
557 throw $this->getDBException( $e );
564 * @see JobQueue::doWaitForBackups()
567 protected function doWaitForBackups() {
568 if ( $this->server
) {
569 return; // not using LBFactory instance
572 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
573 $lbFactory->waitForReplication( [
574 'domain' => $this->domain
,
575 'cluster' => is_string( $this->cluster
) ?
$this->cluster
: false
582 protected function doFlushCaches() {
583 foreach ( [ 'size', 'acquiredcount' ] as $type ) {
584 $this->cache
->delete( $this->getCacheKey( $type ) );
589 * @see JobQueue::getAllQueuedJobs()
592 public function getAllQueuedJobs() {
593 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), 'job_token' => '' ] );
597 * @see JobQueue::getAllAcquiredJobs()
600 public function getAllAcquiredJobs() {
601 return $this->getJobIterator( [ 'job_cmd' => $this->getType(), "job_token > ''" ] );
605 * @param array $conds Query conditions
608 protected function getJobIterator( array $conds ) {
609 $dbr = $this->getReplicaDB();
610 /** @noinspection PhpUnusedLocalVariableInspection */
611 $scope = $this->getScopedNoTrxFlag( $dbr );
613 return new MappedIterator(
614 $dbr->select( 'job', self
::selectFields(), $conds ),
616 return $this->jobFromRow( $row );
619 } catch ( DBError
$e ) {
620 throw $this->getDBException( $e );
624 public function getCoalesceLocationInternal() {
625 if ( $this->server
) {
626 return null; // not using the LBFactory instance
629 return is_string( $this->cluster
)
630 ?
"DBCluster:{$this->cluster}:{$this->domain}"
631 : "LBFactory:{$this->domain}";
634 protected function doGetSiblingQueuesWithJobs( array $types ) {
635 $dbr = $this->getReplicaDB();
636 /** @noinspection PhpUnusedLocalVariableInspection */
637 $scope = $this->getScopedNoTrxFlag( $dbr );
638 // @note: this does not check whether the jobs are claimed or not.
639 // This is useful so JobQueueGroup::pop() also sees queues that only
640 // have stale jobs. This lets recycleAndDeleteStaleJobs() re-enqueue
641 // failed jobs so that they can be popped again for that edge case.
642 $res = $dbr->select( 'job', 'DISTINCT job_cmd',
643 [ 'job_cmd' => $types ], __METHOD__
);
646 foreach ( $res as $row ) {
647 $types[] = $row->job_cmd
;
653 protected function doGetSiblingQueueSizes( array $types ) {
654 $dbr = $this->getReplicaDB();
655 /** @noinspection PhpUnusedLocalVariableInspection */
656 $scope = $this->getScopedNoTrxFlag( $dbr );
658 $res = $dbr->select( 'job', [ 'job_cmd', 'COUNT(*) AS count' ],
659 [ 'job_cmd' => $types ], __METHOD__
, [ 'GROUP BY' => 'job_cmd' ] );
662 foreach ( $res as $row ) {
663 $sizes[$row->job_cmd
] = (int)$row->count
;
670 * Recycle or destroy any jobs that have been claimed for too long
672 * @return int Number of jobs recycled/deleted
674 public function recycleAndDeleteStaleJobs() {
676 $count = 0; // affected rows
677 $dbw = $this->getMasterDB();
678 /** @noinspection PhpUnusedLocalVariableInspection */
679 $scope = $this->getScopedNoTrxFlag( $dbw );
682 if ( !$dbw->lock( "jobqueue-recycle-{$this->type}", __METHOD__
, 1 ) ) {
683 return $count; // already in progress
686 // Remove claims on jobs acquired for too long if enabled...
687 if ( $this->claimTTL
> 0 ) {
688 $claimCutoff = $dbw->timestamp( $now - $this->claimTTL
);
689 // Get the IDs of jobs that have be claimed but not finished after too long.
690 // These jobs can be recycled into the queue by expiring the claim. Selecting
691 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
692 $res = $dbw->select( 'job', 'job_id',
694 'job_cmd' => $this->type
,
695 "job_token != {$dbw->addQuotes( '' )}", // was acquired
696 "job_token_timestamp < {$dbw->addQuotes( $claimCutoff )}", // stale
697 "job_attempts < {$dbw->addQuotes( $this->maxTries )}" ], // retries left
703 }, iterator_to_array( $res )
705 if ( count( $ids ) ) {
706 // Reset job_token for these jobs so that other runners will pick them up.
707 // Set the timestamp to the current time, as it is useful to now that the job
708 // was already tried before (the timestamp becomes the "released" time).
712 'job_token_timestamp' => $dbw->timestamp( $now ) ], // time of release
717 $affected = $dbw->affectedRows();
719 $this->incrStats( 'recycles', $this->type
, $affected );
723 // Just destroy any stale jobs...
724 $pruneCutoff = $dbw->timestamp( $now - self
::MAX_AGE_PRUNE
);
726 'job_cmd' => $this->type
,
727 "job_token != {$dbw->addQuotes( '' )}", // was acquired
728 "job_token_timestamp < {$dbw->addQuotes( $pruneCutoff )}" // stale
730 if ( $this->claimTTL
> 0 ) { // only prune jobs attempted too many times...
731 $conds[] = "job_attempts >= {$dbw->addQuotes( $this->maxTries )}";
733 // Get the IDs of jobs that are considered stale and should be removed. Selecting
734 // the IDs first means that the UPDATE can be done by primary key (less deadlocks).
735 $res = $dbw->select( 'job', 'job_id', $conds, __METHOD__
);
739 }, iterator_to_array( $res )
741 if ( count( $ids ) ) {
742 $dbw->delete( 'job', [ 'job_id' => $ids ], __METHOD__
);
743 $affected = $dbw->affectedRows();
745 $this->incrStats( 'abandons', $this->type
, $affected );
748 $dbw->unlock( "jobqueue-recycle-{$this->type}", __METHOD__
);
749 } catch ( DBError
$e ) {
750 throw $this->getDBException( $e );
757 * @param IJobSpecification $job
758 * @param IDatabase $db
761 protected function insertFields( IJobSpecification
$job, IDatabase
$db ) {
763 // Fields that describe the nature of the job
764 'job_cmd' => $job->getType(),
765 'job_namespace' => $job->getParams()['namespace'] ?? NS_SPECIAL
,
766 'job_title' => $job->getParams()['title'] ??
'',
767 'job_params' => self
::makeBlob( $job->getParams() ),
768 // Additional job metadata
769 'job_timestamp' => $db->timestamp(),
770 'job_sha1' => Wikimedia\base_convert
(
771 sha1( serialize( $job->getDeduplicationInfo() ) ),
774 'job_random' => mt_rand( 0, self
::MAX_JOB_RANDOM
)
779 * @throws JobQueueConnectionError
782 protected function getReplicaDB() {
784 return $this->getDB( DB_REPLICA
);
785 } catch ( DBConnectionError
$e ) {
786 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
791 * @throws JobQueueConnectionError
794 protected function getMasterDB() {
796 return $this->getDB( DB_MASTER
);
797 } catch ( DBConnectionError
$e ) {
798 throw new JobQueueConnectionError( "DBConnectionError:" . $e->getMessage() );
803 * @param int $index (DB_REPLICA/DB_MASTER)
806 protected function getDB( $index ) {
807 if ( $this->server
) {
808 if ( $this->conn
instanceof IDatabase
) {
810 } elseif ( $this->conn
instanceof DBError
) {
815 $this->conn
= Database
::factory( $this->server
['type'], $this->server
);
816 } catch ( DBError
$e ) {
823 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
824 $lb = is_string( $this->cluster
)
825 ?
$lbFactory->getExternalLB( $this->cluster
)
826 : $lbFactory->getMainLB( $this->domain
);
828 return ( $lb->getServerType( $lb->getWriterIndex() ) !== 'sqlite' )
829 // Keep a separate connection to avoid contention and deadlocks;
830 // However, SQLite has the opposite behavior due to DB-level locking.
831 ?
$lb->getConnectionRef( $index, [], $this->domain
, $lb::CONN_TRX_AUTOCOMMIT
)
832 // Jobs insertion will be defered until the PRESEND stage to reduce contention.
833 : $lb->getConnectionRef( $index, [], $this->domain
);
838 * @param IDatabase $db
839 * @return ScopedCallback
841 private function getScopedNoTrxFlag( IDatabase
$db ) {
842 $autoTrx = $db->getFlag( DBO_TRX
); // get current setting
843 $db->clearFlag( DBO_TRX
); // make each query its own transaction
845 return new ScopedCallback( function () use ( $db, $autoTrx ) {
847 $db->setFlag( DBO_TRX
); // restore old setting
853 * @param string $property
856 private function getCacheKey( $property ) {
857 $cluster = is_string( $this->cluster
) ?
$this->cluster
: 'main';
859 return $this->cache
->makeGlobalKey(
869 * @param array|bool $params
872 protected static function makeBlob( $params ) {
873 if ( $params !== false ) {
874 return serialize( $params );
881 * @param stdClass $row
882 * @return RunnableJob|null
884 protected function jobFromRow( $row ) {
885 $params = ( (string)$row->job_params
!== '' ) ?
unserialize( $row->job_params
) : [];
886 if ( !is_array( $params ) ) { // this shouldn't happen
887 throw new UnexpectedValueException(
888 "Could not unserialize job with ID '{$row->job_id}'." );
891 $params +
= [ 'namespace' => $row->job_namespace
, 'title' => $row->job_title
];
892 $job = $this->factoryJob( $row->job_cmd
, $params );
893 $job->setMetadata( 'id', $row->job_id
);
894 $job->setMetadata( 'timestamp', $row->job_timestamp
);
901 * @return JobQueueError
903 protected function getDBException( DBError
$e ) {
904 return new JobQueueError( get_class( $e ) . ": " . $e->getMessage() );
908 * Return the list of job fields that should be selected.
912 public static function selectFields() {
923 'job_token_timestamp',