3 * Interface and manager for deferred updates.
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 MediaWiki\MediaWikiServices
;
24 use Wikimedia\Rdbms\LBFactory
;
25 use Wikimedia\Rdbms\LoadBalancer
;
28 * Class for managing the deferred updates
30 * In web request mode, deferred updates can be run at the end of the request, either before or
31 * after the HTTP response has been sent. In either case, they run after the DB commit step. If
32 * an update runs after the response is sent, it will not block clients. If sent before, it will
33 * run synchronously. These two modes are defined via PRESEND and POSTSEND constants, the latter
34 * being the default for addUpdate() and addCallableUpdate().
36 * Updates that work through this system will be more likely to complete by the time the client
37 * makes their next request after this one than with the JobQueue system.
39 * In CLI mode, deferred updates will run:
40 * - a) During DeferredUpdates::addUpdate if no LBFactory DB handles have writes pending
41 * - b) On commit of an LBFactory DB handle if no other such handles have writes pending
42 * - c) During an LBFactory::waitForReplication call if no LBFactory DBs have writes pending
43 * - d) When the queue is large and an LBFactory DB handle commits (EnqueueableDataUpdate only)
44 * - e) At the completion of Maintenance::execute()
46 * @see Maintenance::setLBFactoryTriggers
48 * When updates are deferred, they go into one two FIFO "top-queues" (one for pre-send and one
49 * for post-send). Updates enqueued *during* doUpdate() of a "top" update go into the "sub-queue"
50 * for that update. After that method finishes, the sub-queue is run until drained. This continues
51 * for each top-queue job until the entire top queue is drained. This happens for the pre-send
52 * top-queue, and later on, the post-send top-queue, in execute().
56 class DeferredUpdates
{
57 /** @var DeferrableUpdate[] Updates to be deferred until before request end */
58 private static $preSendUpdates = [];
59 /** @var DeferrableUpdate[] Updates to be deferred until after request end */
60 private static $postSendUpdates = [];
62 const ALL
= 0; // all updates; in web requests, use only after flushing the output buffer
63 const PRESEND
= 1; // for updates that should run before flushing output buffer
64 const POSTSEND
= 2; // for updates that should run after flushing output buffer
66 const BIG_QUEUE_SIZE
= 100;
68 /** @var array|null Information about the current execute() call or null if not running */
69 private static $executeContext;
72 * Add an update to the deferred list to be run later by execute()
74 * In CLI mode, callback magic will also be used to run updates when safe
76 * @param DeferrableUpdate $update Some object that implements doUpdate()
77 * @param int $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
79 public static function addUpdate( DeferrableUpdate
$update, $stage = self
::POSTSEND
) {
80 global $wgCommandLineMode;
82 if ( self
::$executeContext && self
::$executeContext['stage'] >= $stage ) {
83 // This is a sub-DeferredUpdate; run it right after its parent update.
84 // Also, while post-send updates are running, push any "pre-send" jobs to the
85 // active post-send queue to make sure they get run this round (or at all).
86 self
::$executeContext['subqueue'][] = $update;
91 if ( $stage === self
::PRESEND
) {
92 self
::push( self
::$preSendUpdates, $update );
94 self
::push( self
::$postSendUpdates, $update );
97 // Try to run the updates now if in CLI mode and no transaction is active.
98 // This covers scripts that don't/barely use the DB but make updates to other stores.
99 if ( $wgCommandLineMode ) {
100 self
::tryOpportunisticExecute( 'run' );
105 * Add a callable update. In a lot of cases, we just need a callback/closure,
106 * defining a new DeferrableUpdate object is not necessary
108 * @see MWCallableUpdate::__construct()
110 * @param callable $callable
111 * @param int $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
112 * @param IDatabase|IDatabase[]|null $dbw Abort if this DB is rolled back [optional] (since 1.28)
114 public static function addCallableUpdate(
115 $callable, $stage = self
::POSTSEND
, $dbw = null
117 self
::addUpdate( new MWCallableUpdate( $callable, wfGetCaller(), $dbw ), $stage );
121 * Do any deferred updates and clear the list
123 * @param string $mode Use "enqueue" to use the job queue when possible [Default: "run"]
124 * @param int $stage DeferredUpdates constant (PRESEND, POSTSEND, or ALL) (since 1.27)
126 public static function doUpdates( $mode = 'run', $stage = self
::ALL
) {
127 $stageEffective = ( $stage === self
::ALL
) ? self
::POSTSEND
: $stage;
129 if ( $stage === self
::ALL ||
$stage === self
::PRESEND
) {
130 self
::execute( self
::$preSendUpdates, $mode, $stageEffective );
133 if ( $stage === self
::ALL ||
$stage == self
::POSTSEND
) {
134 self
::execute( self
::$postSendUpdates, $mode, $stageEffective );
139 * @param DeferrableUpdate[] $queue
140 * @param DeferrableUpdate $update
142 private static function push( array &$queue, DeferrableUpdate
$update ) {
143 if ( $update instanceof MergeableUpdate
) {
144 $class = get_class( $update ); // fully-qualified class
145 if ( isset( $queue[$class] ) ) {
146 /** @var MergeableUpdate $existingUpdate */
147 $existingUpdate = $queue[$class];
148 $existingUpdate->merge( $update );
149 // Move the update to the end to handle things like mergeable purge
150 // updates that might depend on the prior updates in the queue running
151 unset( $queue[$class] );
152 $queue[$class] = $existingUpdate;
154 $queue[$class] = $update;
162 * Immediately run/queue a list of updates
164 * @param DeferrableUpdate[] &$queue List of DeferrableUpdate objects
165 * @param string $mode Use "enqueue" to use the job queue when possible
166 * @param int $stage Class constant (PRESEND, POSTSEND) (since 1.28)
167 * @throws ErrorPageError Happens on top-level calls
168 * @throws Exception Happens on second-level calls
170 protected static function execute( array &$queue, $mode, $stage ) {
171 $services = MediaWikiServices
::getInstance();
172 $stats = $services->getStatsdDataFactory();
173 $lbFactory = $services->getDBLoadBalancerFactory();
174 $method = RequestContext
::getMain()->getRequest()->getMethod();
176 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
178 /** @var ErrorPageError $reportableError */
179 $reportableError = null;
180 /** @var DeferrableUpdate[] $updates Snapshot of queue */
183 // Keep doing rounds of updates until none get enqueued...
185 $queue = []; // clear the queue
187 // Order will be DataUpdate followed by generic DeferrableUpdate tasks
188 $updatesByType = [ 'data' => [], 'generic' => [] ];
189 foreach ( $updates as $du ) {
190 if ( $du instanceof DataUpdate
) {
191 $du->setTransactionTicket( $ticket );
192 $updatesByType['data'][] = $du;
194 $updatesByType['generic'][] = $du;
197 $name = ( $du instanceof DeferrableCallback
)
198 ?
get_class( $du ) . '-' . $du->getOrigin()
200 $stats->increment( 'deferred_updates.' . $method . '.' . $name );
203 // Execute all remaining tasks...
204 foreach ( $updatesByType as $updatesForType ) {
205 foreach ( $updatesForType as $update ) {
206 self
::$executeContext = [ 'stage' => $stage, 'subqueue' => [] ];
208 /** @var DeferrableUpdate $update */
209 $guiError = self
::runUpdate( $update, $lbFactory, $mode, $stage );
210 $reportableError = $reportableError ?
: $guiError;
211 // Do the subqueue updates for $update until there are none
212 while ( self
::$executeContext['subqueue'] ) {
213 $subUpdate = reset( self
::$executeContext['subqueue'] );
214 $firstKey = key( self
::$executeContext['subqueue'] );
215 unset( self
::$executeContext['subqueue'][$firstKey] );
217 if ( $subUpdate instanceof DataUpdate
) {
218 $subUpdate->setTransactionTicket( $ticket );
221 $guiError = self
::runUpdate( $subUpdate, $lbFactory, $mode, $stage );
222 $reportableError = $reportableError ?
: $guiError;
225 // Make sure we always clean up the context.
226 // Losing updates while rewinding the stack is acceptable,
227 // losing updates that are added later is not.
228 self
::$executeContext = null;
233 $updates = $queue; // new snapshot of queue (check for new entries)
236 if ( $reportableError ) {
237 throw $reportableError; // throw the first of any GUI errors
242 * @param DeferrableUpdate $update
243 * @param LBFactory $lbFactory
244 * @param string $mode
246 * @return ErrorPageError|null
248 private static function runUpdate(
249 DeferrableUpdate
$update, LBFactory
$lbFactory, $mode, $stage
253 if ( $mode === 'enqueue' && $update instanceof EnqueueableDataUpdate
) {
254 // Run only the job enqueue logic to complete the update later
255 $spec = $update->getAsJobSpecification();
256 JobQueueGroup
::singleton( $spec['wiki'] )->push( $spec['job'] );
257 } elseif ( $update instanceof TransactionRoundDefiningUpdate
) {
260 // Run the bulk of the update now
261 $fnameTrxOwner = get_class( $update ) . '::doUpdate';
262 $lbFactory->beginMasterChanges( $fnameTrxOwner );
264 $lbFactory->commitMasterChanges( $fnameTrxOwner );
266 } catch ( Exception
$e ) {
267 // Reporting GUI exceptions does not work post-send
268 if ( $e instanceof ErrorPageError
&& $stage === self
::PRESEND
) {
271 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
273 // VW-style hack to work around T190178, so we can make sure
274 // PageMetaDataUpdater doesn't throw exceptions.
275 if ( defined( 'MW_PHPUNIT_TEST' ) ) {
284 * Run all deferred updates immediately if there are no DB writes active
286 * If there are many deferred updates pending, $mode is 'run', and there
287 * are still busy LBFactory database handles, then any EnqueueableDataUpdate
288 * tasks might be enqueued as jobs to be executed later.
290 * @param string $mode Use "enqueue" to use the job queue when possible
291 * @return bool Whether updates were allowed to run
294 public static function tryOpportunisticExecute( $mode = 'run' ) {
295 // execute() loop is already running
296 if ( self
::$executeContext ) {
300 // Avoiding running updates without them having outer scope
301 if ( !self
::areDatabaseTransactionsActive() ) {
302 self
::doUpdates( $mode );
306 if ( self
::pendingUpdatesCount() >= self
::BIG_QUEUE_SIZE
) {
307 // If we cannot run the updates with outer transaction context, try to
308 // at least enqueue all the updates that support queueing to job queue
309 self
::$preSendUpdates = self
::enqueueUpdates( self
::$preSendUpdates );
310 self
::$postSendUpdates = self
::enqueueUpdates( self
::$postSendUpdates );
313 return !self
::pendingUpdatesCount();
317 * Enqueue a job for each EnqueueableDataUpdate item and return the other items
319 * @param DeferrableUpdate[] $updates A list of deferred update instances
320 * @return DeferrableUpdate[] Remaining updates that do not support being queued
322 private static function enqueueUpdates( array $updates ) {
325 foreach ( $updates as $update ) {
326 if ( $update instanceof EnqueueableDataUpdate
) {
327 $spec = $update->getAsJobSpecification();
328 JobQueueGroup
::singleton( $spec['wiki'] )->push( $spec['job'] );
330 $remaining[] = $update;
338 * @return int Number of enqueued updates
341 public static function pendingUpdatesCount() {
342 return count( self
::$preSendUpdates ) +
count( self
::$postSendUpdates );
346 * @param int $stage DeferredUpdates constant (PRESEND, POSTSEND, or ALL)
347 * @return DeferrableUpdate[]
350 public static function getPendingUpdates( $stage = self
::ALL
) {
352 if ( $stage === self
::ALL ||
$stage === self
::PRESEND
) {
353 $updates = array_merge( $updates, self
::$preSendUpdates );
355 if ( $stage === self
::ALL ||
$stage === self
::POSTSEND
) {
356 $updates = array_merge( $updates, self
::$postSendUpdates );
362 * Clear all pending updates without performing them. Generally, you don't
363 * want or need to call this. Unit tests need it though.
365 public static function clearPendingUpdates() {
366 self
::$preSendUpdates = [];
367 self
::$postSendUpdates = [];
371 * @return bool If a transaction round is active or connection is not ready for commit()
373 private static function areDatabaseTransactionsActive() {
374 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
375 if ( $lbFactory->hasTransactionRound() ||
!$lbFactory->isReadyForRoundOperations() ) {
380 $lbFactory->forEachLB( function ( LoadBalancer
$lb ) use ( &$connsBusy ) {
381 $lb->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$connsBusy ) {
382 if ( $conn->writesOrCallbacksPending() ||
$conn->explicitTrxActive() ) {