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 MediaWiki\MediaWikiServices
;
25 * Class for managing the deferred updates
27 * In web request mode, deferred updates can be run at the end of the request, either before or
28 * after the HTTP response has been sent. In either case, they run after the DB commit step. If
29 * an update runs after the response is sent, it will not block clients. If sent before, it will
30 * run synchronously. If such an update works via queueing, it will be more likely to complete by
31 * the time the client makes their next request after this one.
33 * In CLI mode, updates run immediately if no DB writes are pending. Otherwise, they run when:
34 * - a) Any waitForReplication() call if no writes are pending on any DB
35 * - b) A commit happens on Maintenance::getDB( DB_MASTER ) if no writes are pending on any DB
36 * - c) EnqueueableDataUpdate tasks may enqueue on commit of Maintenance::getDB( DB_MASTER )
37 * - d) At the completion of Maintenance::execute()
39 * When updates are deferred, they use a FIFO queue (one for pre-send and one for post-send).
43 class DeferredUpdates
{
44 /** @var DeferrableUpdate[] Updates to be deferred until before request end */
45 private static $preSendUpdates = [];
46 /** @var DeferrableUpdate[] Updates to be deferred until after request end */
47 private static $postSendUpdates = [];
49 const ALL
= 0; // all updates; in web requests, use only after flushing the output buffer
50 const PRESEND
= 1; // for updates that should run before flushing output buffer
51 const POSTSEND
= 2; // for updates that should run after flushing output buffer
53 const BIG_QUEUE_SIZE
= 100;
55 /** @var array|null Information about the current execute() call or null if not running */
56 private static $executeContext;
59 * Add an update to the deferred list to be run later by execute()
61 * In CLI mode, callback magic will also be used to run updates when safe
63 * @param DeferrableUpdate $update Some object that implements doUpdate()
64 * @param integer $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
66 public static function addUpdate( DeferrableUpdate
$update, $stage = self
::POSTSEND
) {
67 global $wgCommandLineMode;
69 // This is a sub-DeferredUpdate, run it right after its parent update
70 if ( self
::$executeContext && self
::$executeContext['stage'] >= $stage ) {
71 self
::$executeContext['subqueue'][] = $update;
75 if ( $stage === self
::PRESEND
) {
76 self
::push( self
::$preSendUpdates, $update );
78 self
::push( self
::$postSendUpdates, $update );
81 // Try to run the updates now if in CLI mode and no transaction is active.
82 // This covers scripts that don't/barely use the DB but make updates to other stores.
83 if ( $wgCommandLineMode ) {
84 self
::tryOpportunisticExecute( 'run' );
89 * Add a callable update. In a lot of cases, we just need a callback/closure,
90 * defining a new DeferrableUpdate object is not necessary
92 * @see MWCallableUpdate::__construct()
94 * @param callable $callable
95 * @param integer $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
96 * @param IDatabase|null $dbw Abort if this DB is rolled back [optional] (since 1.28)
98 public static function addCallableUpdate(
99 $callable, $stage = self
::POSTSEND
, IDatabase
$dbw = null
101 self
::addUpdate( new MWCallableUpdate( $callable, wfGetCaller(), $dbw ), $stage );
105 * Do any deferred updates and clear the list
107 * @param string $mode Use "enqueue" to use the job queue when possible [Default: "run"]
108 * @param integer $stage DeferredUpdates constant (PRESEND, POSTSEND, or ALL) (since 1.27)
110 public static function doUpdates( $mode = 'run', $stage = self
::ALL
) {
111 $stageEffective = ( $stage === self
::ALL
) ? self
::POSTSEND
: $stage;
113 if ( $stage === self
::ALL ||
$stage === self
::PRESEND
) {
114 self
::execute( self
::$preSendUpdates, $mode, $stageEffective );
117 if ( $stage === self
::ALL ||
$stage == self
::POSTSEND
) {
118 self
::execute( self
::$postSendUpdates, $mode, $stageEffective );
123 * @param DeferrableUpdate[] $queue
124 * @param DeferrableUpdate $update
126 private static function push( array &$queue, DeferrableUpdate
$update ) {
127 if ( $update instanceof MergeableUpdate
) {
128 $class = get_class( $update ); // fully-qualified class
129 if ( isset( $queue[$class] ) ) {
130 /** @var $existingUpdate MergeableUpdate */
131 $existingUpdate = $queue[$class];
132 $existingUpdate->merge( $update );
134 $queue[$class] = $update;
142 * @param DeferrableUpdate[] &$queue List of DeferrableUpdate objects
143 * @param string $mode Use "enqueue" to use the job queue when possible
144 * @param integer $stage Class constant (PRESEND, POSTSEND) (since 1.28)
145 * @throws ErrorPageError Happens on top-level calls
146 * @throws Exception Happens on second-level calls
148 public static function execute( array &$queue, $mode, $stage ) {
149 $services = MediaWikiServices
::getInstance();
150 $stats = $services->getStatsdDataFactory();
151 $lbFactory = $services->getDBLoadBalancerFactory();
152 $method = RequestContext
::getMain()->getRequest()->getMethod();
154 /** @var ErrorPageError $reportableError */
155 $reportableError = null;
156 /** @var DeferrableUpdate[] $updates Snapshot of queue */
159 // Keep doing rounds of updates until none get enqueued...
161 $queue = []; // clear the queue
163 if ( $mode === 'enqueue' ) {
165 // Push enqueuable updates to the job queue and get the rest
166 $updates = self
::enqueueUpdates( $updates );
167 } catch ( Exception
$e ) {
168 // Let other updates have a chance to run if this failed
169 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
173 // Order will be DataUpdate followed by generic DeferrableUpdate tasks
174 $updatesByType = [ 'data' => [], 'generic' => [] ];
175 foreach ( $updates as $du ) {
176 $updatesByType[$du instanceof DataUpdate ?
'data' : 'generic'][] = $du;
177 $name = ( $du instanceof DeferrableCallback
)
178 ?
get_class( $du ) . '-' . $du->getOrigin()
180 $stats->increment( 'deferred_updates.' . $method . '.' . $name );
183 // Execute all remaining tasks...
184 foreach ( $updatesByType as $updatesForType ) {
185 foreach ( $updatesForType as $update ) {
186 self
::$executeContext = [
191 /** @var DeferrableUpdate $update */
192 $guiError = self
::runUpdate( $update, $lbFactory, $stage );
193 $reportableError = $reportableError ?
: $guiError;
194 // Do the subqueue updates for $update until there are none
195 while ( self
::$executeContext['subqueue'] ) {
196 $subUpdate = reset( self
::$executeContext['subqueue'] );
197 $firstKey = key( self
::$executeContext['subqueue'] );
198 unset( self
::$executeContext['subqueue'][$firstKey] );
200 $guiError = self
::runUpdate( $subUpdate, $lbFactory, $stage );
201 $reportableError = $reportableError ?
: $guiError;
203 self
::$executeContext = null;
207 $updates = $queue; // new snapshot of queue (check for new entries)
210 if ( $reportableError ) {
211 throw $reportableError; // throw the first of any GUI errors
216 * @param DeferrableUpdate $update
217 * @param LBFactory $lbFactory
218 * @param integer $stage
219 * @return ErrorPageError|null
221 private static function runUpdate( DeferrableUpdate
$update, LBFactory
$lbFactory, $stage ) {
224 $fnameTrxOwner = get_class( $update ) . '::doUpdate';
225 $lbFactory->beginMasterChanges( $fnameTrxOwner );
227 $lbFactory->commitMasterChanges( $fnameTrxOwner );
228 } catch ( Exception
$e ) {
229 // Reporting GUI exceptions does not work post-send
230 if ( $e instanceof ErrorPageError
&& $stage === self
::PRESEND
) {
233 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
240 * Run all deferred updates immediately if there are no DB writes active
242 * If $mode is 'run' but there are busy databates, EnqueueableDataUpdate
243 * tasks will be enqueued anyway for the sake of progress.
245 * @param string $mode Use "enqueue" to use the job queue when possible
246 * @return bool Whether updates were allowed to run
249 public static function tryOpportunisticExecute( $mode = 'run' ) {
250 // execute() loop is already running
251 if ( self
::$executeContext ) {
255 // Avoiding running updates without them having outer scope
256 if ( !self
::getBusyDbConnections() ) {
257 self
::doUpdates( $mode );
261 if ( self
::pendingUpdatesCount() >= self
::BIG_QUEUE_SIZE
) {
262 // If we cannot run the updates with outer transaction context, try to
263 // at least enqueue all the updates that support queueing to job queue
264 self
::$preSendUpdates = self
::enqueueUpdates( self
::$preSendUpdates );
265 self
::$postSendUpdates = self
::enqueueUpdates( self
::$postSendUpdates );
268 return !self
::pendingUpdatesCount();
272 * Enqueue a job for each EnqueueableDataUpdate item and return the other items
274 * @param DeferrableUpdate[] $updates A list of deferred update instances
275 * @return DeferrableUpdate[] Remaining updates that do not support being queued
277 private static function enqueueUpdates( array $updates ) {
280 foreach ( $updates as $update ) {
281 if ( $update instanceof EnqueueableDataUpdate
) {
282 $spec = $update->getAsJobSpecification();
283 JobQueueGroup
::singleton( $spec['wiki'] )->push( $spec['job'] );
285 $remaining[] = $update;
293 * @return integer Number of enqueued updates
296 public static function pendingUpdatesCount() {
297 return count( self
::$preSendUpdates ) +
count( self
::$postSendUpdates );
301 * Clear all pending updates without performing them. Generally, you don't
302 * want or need to call this. Unit tests need it though.
304 public static function clearPendingUpdates() {
305 self
::$preSendUpdates = [];
306 self
::$postSendUpdates = [];
310 * @return IDatabase[] Connection where commit() cannot be called yet
312 private static function getBusyDbConnections() {
315 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
316 $lbFactory->forEachLB( function ( LoadBalancer
$lb ) use ( &$connsBusy ) {
317 $lb->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$connsBusy ) {
318 if ( $conn->writesOrCallbacksPending() ||
$conn->explicitTrxActive() ) {
319 $connsBusy[] = $conn;