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\ILBFactory
;
26 use Wikimedia\Rdbms\LoadBalancer
;
29 * Class for managing the deferred updates
31 * In web request mode, deferred updates can be run at the end of the request, either before or
32 * after the HTTP response has been sent. In either case, they run after the DB commit step. If
33 * an update runs after the response is sent, it will not block clients. If sent before, it will
34 * run synchronously. These two modes are defined via PRESEND and POSTSEND constants, the latter
35 * being the default for addUpdate() and addCallableUpdate().
37 * Updates that work through this system will be more likely to complete by the time the client
38 * makes their next request after this one than with the JobQueue system.
40 * In CLI mode, deferred updates will run:
41 * - a) During DeferredUpdates::addUpdate if no LBFactory DB handles have writes pending
42 * - b) On commit of an LBFactory DB handle if no other such handles have writes pending
43 * - c) During an LBFactory::waitForReplication call if no LBFactory DBs have writes pending
44 * - d) When the queue is large and an LBFactory DB handle commits (EnqueueableDataUpdate only)
45 * - e) At the completion of Maintenance::execute()
47 * @see Maintenance::setLBFactoryTriggers
49 * When updates are deferred, they go into one two FIFO "top-queues" (one for pre-send and one
50 * for post-send). Updates enqueued *during* doUpdate() of a "top" update go into the "sub-queue"
51 * for that update. After that method finishes, the sub-queue is run until drained. This continues
52 * for each top-queue job until the entire top queue is drained. This happens for the pre-send
53 * top-queue, and later on, the post-send top-queue, in execute().
57 class DeferredUpdates
{
58 /** @var DeferrableUpdate[] Updates to be deferred until before request end */
59 private static $preSendUpdates = [];
60 /** @var DeferrableUpdate[] Updates to be deferred until after request end */
61 private static $postSendUpdates = [];
63 const ALL
= 0; // all updates; in web requests, use only after flushing the output buffer
64 const PRESEND
= 1; // for updates that should run before flushing output buffer
65 const POSTSEND
= 2; // for updates that should run after flushing output buffer
67 const BIG_QUEUE_SIZE
= 100;
69 /** @var array|null Information about the current execute() call or null if not running */
70 private static $executeContext;
73 * Add an update to the deferred list to be run later by execute()
75 * In CLI mode, callback magic will also be used to run updates when safe
77 * @param DeferrableUpdate $update Some object that implements doUpdate()
78 * @param int $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
80 public static function addUpdate( DeferrableUpdate
$update, $stage = self
::POSTSEND
) {
81 global $wgCommandLineMode;
84 self
::$executeContext &&
85 self
::$executeContext['stage'] >= $stage &&
86 !( $update instanceof MergeableUpdate
)
88 // This is a sub-DeferredUpdate; run it right after its parent update.
89 // Also, while post-send updates are running, push any "pre-send" jobs to the
90 // active post-send queue to make sure they get run this round (or at all).
91 self
::$executeContext['subqueue'][] = $update;
96 if ( $stage === self
::PRESEND
) {
97 self
::push( self
::$preSendUpdates, $update );
99 self
::push( self
::$postSendUpdates, $update );
102 // Try to run the updates now if in CLI mode and no transaction is active.
103 // This covers scripts that don't/barely use the DB but make updates to other stores.
104 if ( $wgCommandLineMode ) {
105 self
::tryOpportunisticExecute( 'run' );
110 * Add a callable update. In a lot of cases, we just need a callback/closure,
111 * defining a new DeferrableUpdate object is not necessary
113 * @see MWCallableUpdate::__construct()
115 * @param callable $callable
116 * @param int $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
117 * @param IDatabase|IDatabase[]|null $dbw Abort if this DB is rolled back [optional] (since 1.28)
119 public static function addCallableUpdate(
120 $callable, $stage = self
::POSTSEND
, $dbw = null
122 self
::addUpdate( new MWCallableUpdate( $callable, wfGetCaller(), $dbw ), $stage );
126 * Do any deferred updates and clear the list
128 * If $stage is self::ALL then the queue of PRESEND updates will be resolved,
129 * followed by the queue of POSTSEND updates
131 * @param string $mode Use "enqueue" to use the job queue when possible [Default: "run"]
132 * @param int $stage DeferredUpdates constant (PRESEND, POSTSEND, or ALL) (since 1.27)
134 public static function doUpdates( $mode = 'run', $stage = self
::ALL
) {
135 $stageEffective = ( $stage === self
::ALL
) ? self
::POSTSEND
: $stage;
136 // For ALL mode, make sure that any PRESEND updates added along the way get run.
137 // Normally, these use the subqueue, but that isn't true for MergeableUpdate items.
139 if ( $stage === self
::ALL ||
$stage === self
::PRESEND
) {
140 self
::handleUpdateQueue( self
::$preSendUpdates, $mode, $stageEffective );
143 if ( $stage === self
::ALL ||
$stage == self
::POSTSEND
) {
144 self
::handleUpdateQueue( self
::$postSendUpdates, $mode, $stageEffective );
146 } while ( $stage === self
::ALL
&& self
::$preSendUpdates );
150 * @param DeferrableUpdate[] $queue
151 * @param DeferrableUpdate $update
153 private static function push( array &$queue, DeferrableUpdate
$update ) {
154 if ( $update instanceof MergeableUpdate
) {
155 $class = get_class( $update ); // fully-qualified class
156 if ( isset( $queue[$class] ) ) {
157 /** @var MergeableUpdate $existingUpdate */
158 $existingUpdate = $queue[$class];
159 $existingUpdate->merge( $update );
160 // Move the update to the end to handle things like mergeable purge
161 // updates that might depend on the prior updates in the queue running
162 unset( $queue[$class] );
163 $queue[$class] = $existingUpdate;
165 $queue[$class] = $update;
173 * Immediately run or enqueue a list of updates
175 * @param DeferrableUpdate[] &$queue List of DeferrableUpdate objects
176 * @param string $mode Either "run" or "enqueue" (to use the job queue when possible)
177 * @param int $stage Class constant (PRESEND, POSTSEND) (since 1.28)
178 * @throws ErrorPageError Happens on top-level calls
179 * @throws Exception Happens on second-level calls
181 protected static function handleUpdateQueue( array &$queue, $mode, $stage ) {
182 $services = MediaWikiServices
::getInstance();
183 $stats = $services->getStatsdDataFactory();
184 $lbFactory = $services->getDBLoadBalancerFactory();
185 $method = RequestContext
::getMain()->getRequest()->getMethod();
187 /** @var ErrorPageError $reportableError */
188 $reportableError = null;
189 /** @var DeferrableUpdate[] $updates Snapshot of queue */
192 // Keep doing rounds of updates until none get enqueued...
194 $queue = []; // clear the queue
196 // Order will be DataUpdate followed by generic DeferrableUpdate tasks
197 $updatesByType = [ 'data' => [], 'generic' => [] ];
198 foreach ( $updates as $du ) {
199 if ( $du instanceof DataUpdate
) {
200 $updatesByType['data'][] = $du;
202 $updatesByType['generic'][] = $du;
205 $name = ( $du instanceof DeferrableCallback
)
206 ?
get_class( $du ) . '-' . $du->getOrigin()
208 $stats->increment( 'deferred_updates.' . $method . '.' . $name );
211 // Execute all remaining tasks...
212 foreach ( $updatesByType as $updatesForType ) {
213 foreach ( $updatesForType as $update ) {
214 self
::$executeContext = [ 'stage' => $stage, 'subqueue' => [] ];
216 /** @var DeferrableUpdate $update */
217 $guiError = self
::handleUpdate( $update, $lbFactory, $mode, $stage );
218 $reportableError = $reportableError ?
: $guiError;
219 // Do the subqueue updates for $update until there are none
220 while ( self
::$executeContext['subqueue'] ) {
221 $subUpdate = reset( self
::$executeContext['subqueue'] );
222 $firstKey = key( self
::$executeContext['subqueue'] );
223 unset( self
::$executeContext['subqueue'][$firstKey] );
225 $guiError = self
::handleUpdate( $subUpdate, $lbFactory, $mode, $stage );
226 $reportableError = $reportableError ?
: $guiError;
229 // Make sure we always clean up the context.
230 // Losing updates while rewinding the stack is acceptable,
231 // losing updates that are added later is not.
232 self
::$executeContext = null;
237 $updates = $queue; // new snapshot of queue (check for new entries)
240 if ( $reportableError ) {
241 throw $reportableError; // throw the first of any GUI errors
246 * Run or enqueue an update
248 * @param DeferrableUpdate $update
249 * @param LBFactory $lbFactory
250 * @param string $mode
252 * @return ErrorPageError|null
254 private static function handleUpdate(
255 DeferrableUpdate
$update, LBFactory
$lbFactory, $mode, $stage
259 if ( $mode === 'enqueue' && $update instanceof EnqueueableDataUpdate
) {
260 // Run only the job enqueue logic to complete the update later
261 $spec = $update->getAsJobSpecification();
262 $domain = $spec['domain'] ??
$spec['wiki'];
263 JobQueueGroup
::singleton( $domain )->push( $spec['job'] );
265 self
::attemptUpdate( $update, $lbFactory );
267 } catch ( Exception
$e ) {
268 // Reporting GUI exceptions does not work post-send
269 if ( $e instanceof ErrorPageError
&& $stage === self
::PRESEND
) {
272 $lbFactory->rollbackMasterChanges( __METHOD__
);
274 // VW-style hack to work around T190178, so we can make sure
275 // PageMetaDataUpdater doesn't throw exceptions.
276 if ( defined( 'MW_PHPUNIT_TEST' ) ) {
285 * Attempt to run an update with the appropriate transaction round state it expects
287 * DeferredUpdate classes that wrap the execution of bundles of other DeferredUpdate
288 * instances can use this method to run the updates. Any such wrapper class should
289 * always use TRX_ROUND_ABSENT itself.
291 * @param DeferrableUpdate $update
292 * @param ILBFactory $lbFactory
295 public static function attemptUpdate( DeferrableUpdate
$update, ILBFactory
$lbFactory ) {
296 if ( $update instanceof DataUpdate
) {
297 $update->setTransactionTicket( $lbFactory->getEmptyTransactionTicket( __METHOD__
) );
301 $update instanceof TransactionRoundAwareUpdate
&&
302 $update->getTransactionRoundRequirement() == $update::TRX_ROUND_ABSENT
306 // Run the bulk of the update now
307 $fnameTrxOwner = get_class( $update ) . '::doUpdate';
308 $lbFactory->beginMasterChanges( $fnameTrxOwner );
310 $lbFactory->commitMasterChanges( $fnameTrxOwner );
315 * Run all deferred updates immediately if there are no DB writes active
317 * If there are many deferred updates pending, $mode is 'run', and there
318 * are still busy LBFactory database handles, then any EnqueueableDataUpdate
319 * tasks might be enqueued as jobs to be executed later.
321 * @param string $mode Use "enqueue" to use the job queue when possible
322 * @return bool Whether updates were allowed to run
325 public static function tryOpportunisticExecute( $mode = 'run' ) {
326 // execute() loop is already running
327 if ( self
::$executeContext ) {
331 // Avoiding running updates without them having outer scope
332 if ( !self
::areDatabaseTransactionsActive() ) {
333 self
::doUpdates( $mode );
337 if ( self
::pendingUpdatesCount() >= self
::BIG_QUEUE_SIZE
) {
338 // If we cannot run the updates with outer transaction context, try to
339 // at least enqueue all the updates that support queueing to job queue
340 self
::$preSendUpdates = self
::enqueueUpdates( self
::$preSendUpdates );
341 self
::$postSendUpdates = self
::enqueueUpdates( self
::$postSendUpdates );
344 return !self
::pendingUpdatesCount();
348 * Enqueue a job for each EnqueueableDataUpdate item and return the other items
350 * @param DeferrableUpdate[] $updates A list of deferred update instances
351 * @return DeferrableUpdate[] Remaining updates that do not support being queued
353 private static function enqueueUpdates( array $updates ) {
356 foreach ( $updates as $update ) {
357 if ( $update instanceof EnqueueableDataUpdate
) {
358 $spec = $update->getAsJobSpecification();
359 $domain = $spec['domain'] ??
$spec['wiki'];
360 JobQueueGroup
::singleton( $domain )->push( $spec['job'] );
362 $remaining[] = $update;
370 * @return int Number of enqueued updates
373 public static function pendingUpdatesCount() {
374 return count( self
::$preSendUpdates ) +
count( self
::$postSendUpdates );
378 * @param int $stage DeferredUpdates constant (PRESEND, POSTSEND, or ALL)
379 * @return DeferrableUpdate[]
382 public static function getPendingUpdates( $stage = self
::ALL
) {
384 if ( $stage === self
::ALL ||
$stage === self
::PRESEND
) {
385 $updates = array_merge( $updates, self
::$preSendUpdates );
387 if ( $stage === self
::ALL ||
$stage === self
::POSTSEND
) {
388 $updates = array_merge( $updates, self
::$postSendUpdates );
394 * Clear all pending updates without performing them. Generally, you don't
395 * want or need to call this. Unit tests need it though.
397 public static function clearPendingUpdates() {
398 self
::$preSendUpdates = [];
399 self
::$postSendUpdates = [];
403 * @return bool If a transaction round is active or connection is not ready for commit()
405 private static function areDatabaseTransactionsActive() {
406 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
407 if ( $lbFactory->hasTransactionRound() ||
!$lbFactory->isReadyForRoundOperations() ) {
412 $lbFactory->forEachLB( function ( LoadBalancer
$lb ) use ( &$connsBusy ) {
413 $lb->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$connsBusy ) {
414 if ( $conn->writesOrCallbacksPending() ||
$conn->explicitTrxActive() ) {