Merge "Use {{int:}} on MediaWiki:Blockedtext and MediaWiki:Autoblockedtext"
[lhc/web/wiklou.git] / includes / deferred / DeferredUpdates.php
1 <?php
2 /**
3 * Interface and manager for deferred updates.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22 use Wikimedia\Rdbms\IDatabase;
23 use MediaWiki\MediaWikiServices;
24 use Wikimedia\Rdbms\LBFactory;
25 use Wikimedia\Rdbms\LoadBalancer;
26
27 /**
28 * Class for managing the deferred updates
29 *
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().
35 *
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.
38 *
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()
45 *
46 * @see Maintenance::setLBFactoryTriggers
47 *
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().
53 *
54 * @since 1.19
55 */
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 = [];
61
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
65
66 const BIG_QUEUE_SIZE = 100;
67
68 /** @var array|null Information about the current execute() call or null if not running */
69 private static $executeContext;
70
71 /**
72 * Add an update to the deferred list to be run later by execute()
73 *
74 * In CLI mode, callback magic will also be used to run updates when safe
75 *
76 * @param DeferrableUpdate $update Some object that implements doUpdate()
77 * @param int $stage DeferredUpdates constant (PRESEND or POSTSEND) (since 1.27)
78 */
79 public static function addUpdate( DeferrableUpdate $update, $stage = self::POSTSEND ) {
80 global $wgCommandLineMode;
81
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;
87
88 return;
89 }
90
91 if ( $stage === self::PRESEND ) {
92 self::push( self::$preSendUpdates, $update );
93 } else {
94 self::push( self::$postSendUpdates, $update );
95 }
96
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' );
101 }
102 }
103
104 /**
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
107 *
108 * @see MWCallableUpdate::__construct()
109 *
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)
113 */
114 public static function addCallableUpdate(
115 $callable, $stage = self::POSTSEND, $dbw = null
116 ) {
117 self::addUpdate( new MWCallableUpdate( $callable, wfGetCaller(), $dbw ), $stage );
118 }
119
120 /**
121 * Do any deferred updates and clear the list
122 *
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)
125 */
126 public static function doUpdates( $mode = 'run', $stage = self::ALL ) {
127 $stageEffective = ( $stage === self::ALL ) ? self::POSTSEND : $stage;
128
129 if ( $stage === self::ALL || $stage === self::PRESEND ) {
130 self::execute( self::$preSendUpdates, $mode, $stageEffective );
131 }
132
133 if ( $stage === self::ALL || $stage == self::POSTSEND ) {
134 self::execute( self::$postSendUpdates, $mode, $stageEffective );
135 }
136 }
137
138 /**
139 * @param bool $value Whether to just immediately run updates in addUpdate()
140 * @since 1.28
141 * @deprecated 1.29 Causes issues in Web-executed jobs - see T165714 and T100085.
142 */
143 public static function setImmediateMode( $value ) {
144 wfDeprecated( __METHOD__, '1.29' );
145 }
146
147 /**
148 * @param DeferrableUpdate[] $queue
149 * @param DeferrableUpdate $update
150 */
151 private static function push( array &$queue, DeferrableUpdate $update ) {
152 if ( $update instanceof MergeableUpdate ) {
153 $class = get_class( $update ); // fully-qualified class
154 if ( isset( $queue[$class] ) ) {
155 /** @var MergeableUpdate $existingUpdate */
156 $existingUpdate = $queue[$class];
157 $existingUpdate->merge( $update );
158 } else {
159 $queue[$class] = $update;
160 }
161 } else {
162 $queue[] = $update;
163 }
164 }
165
166 /**
167 * Immediately run/queue a list of updates
168 *
169 * @param DeferrableUpdate[] &$queue List of DeferrableUpdate objects
170 * @param string $mode Use "enqueue" to use the job queue when possible
171 * @param int $stage Class constant (PRESEND, POSTSEND) (since 1.28)
172 * @throws ErrorPageError Happens on top-level calls
173 * @throws Exception Happens on second-level calls
174 */
175 protected static function execute( array &$queue, $mode, $stage ) {
176 $services = MediaWikiServices::getInstance();
177 $stats = $services->getStatsdDataFactory();
178 $lbFactory = $services->getDBLoadBalancerFactory();
179 $method = RequestContext::getMain()->getRequest()->getMethod();
180
181 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
182
183 /** @var ErrorPageError $reportableError */
184 $reportableError = null;
185 /** @var DeferrableUpdate[] $updates Snapshot of queue */
186 $updates = $queue;
187
188 // Keep doing rounds of updates until none get enqueued...
189 while ( $updates ) {
190 $queue = []; // clear the queue
191
192 // Order will be DataUpdate followed by generic DeferrableUpdate tasks
193 $updatesByType = [ 'data' => [], 'generic' => [] ];
194 foreach ( $updates as $du ) {
195 if ( $du instanceof DataUpdate ) {
196 $du->setTransactionTicket( $ticket );
197 $updatesByType['data'][] = $du;
198 } else {
199 $updatesByType['generic'][] = $du;
200 }
201
202 $name = ( $du instanceof DeferrableCallback )
203 ? get_class( $du ) . '-' . $du->getOrigin()
204 : get_class( $du );
205 $stats->increment( 'deferred_updates.' . $method . '.' . $name );
206 }
207
208 // Execute all remaining tasks...
209 foreach ( $updatesByType as $updatesForType ) {
210 foreach ( $updatesForType as $update ) {
211 self::$executeContext = [ 'stage' => $stage, 'subqueue' => [] ];
212 try {
213 /** @var DeferrableUpdate $update */
214 $guiError = self::runUpdate( $update, $lbFactory, $mode, $stage );
215 $reportableError = $reportableError ?: $guiError;
216 // Do the subqueue updates for $update until there are none
217 while ( self::$executeContext['subqueue'] ) {
218 $subUpdate = reset( self::$executeContext['subqueue'] );
219 $firstKey = key( self::$executeContext['subqueue'] );
220 unset( self::$executeContext['subqueue'][$firstKey] );
221
222 if ( $subUpdate instanceof DataUpdate ) {
223 $subUpdate->setTransactionTicket( $ticket );
224 }
225
226 $guiError = self::runUpdate( $subUpdate, $lbFactory, $mode, $stage );
227 $reportableError = $reportableError ?: $guiError;
228 }
229 } finally {
230 // Make sure we always clean up the context.
231 // Losing updates while rewinding the stack is acceptable,
232 // losing updates that are added later is not.
233 self::$executeContext = null;
234 }
235 }
236 }
237
238 $updates = $queue; // new snapshot of queue (check for new entries)
239 }
240
241 if ( $reportableError ) {
242 throw $reportableError; // throw the first of any GUI errors
243 }
244 }
245
246 /**
247 * @param DeferrableUpdate $update
248 * @param LBFactory $lbFactory
249 * @param string $mode
250 * @param int $stage
251 * @return ErrorPageError|null
252 */
253 private static function runUpdate(
254 DeferrableUpdate $update, LBFactory $lbFactory, $mode, $stage
255 ) {
256 $guiError = null;
257 try {
258 if ( $mode === 'enqueue' && $update instanceof EnqueueableDataUpdate ) {
259 // Run only the job enqueue logic to complete the update later
260 $spec = $update->getAsJobSpecification();
261 JobQueueGroup::singleton( $spec['wiki'] )->push( $spec['job'] );
262 } elseif ( $update instanceof TransactionRoundDefiningUpdate ) {
263 $update->doUpdate();
264 } else {
265 // Run the bulk of the update now
266 $fnameTrxOwner = get_class( $update ) . '::doUpdate';
267 $lbFactory->beginMasterChanges( $fnameTrxOwner );
268 $update->doUpdate();
269 $lbFactory->commitMasterChanges( $fnameTrxOwner );
270 }
271 } catch ( Exception $e ) {
272 // Reporting GUI exceptions does not work post-send
273 if ( $e instanceof ErrorPageError && $stage === self::PRESEND ) {
274 $guiError = $e;
275 }
276 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
277
278 // VW-style hack to work around T190178, so we can make sure
279 // PageMetaDataUpdater doesn't throw exceptions.
280 if ( defined( 'MW_PHPUNIT_TEST' ) ) {
281 throw $e;
282 }
283 }
284
285 return $guiError;
286 }
287
288 /**
289 * Run all deferred updates immediately if there are no DB writes active
290 *
291 * If there are many deferred updates pending, $mode is 'run', and there
292 * are still busy LBFactory database handles, then any EnqueueableDataUpdate
293 * tasks might be enqueued as jobs to be executed later.
294 *
295 * @param string $mode Use "enqueue" to use the job queue when possible
296 * @return bool Whether updates were allowed to run
297 * @since 1.28
298 */
299 public static function tryOpportunisticExecute( $mode = 'run' ) {
300 // execute() loop is already running
301 if ( self::$executeContext ) {
302 return false;
303 }
304
305 // Avoiding running updates without them having outer scope
306 if ( !self::areDatabaseTransactionsActive() ) {
307 self::doUpdates( $mode );
308 return true;
309 }
310
311 if ( self::pendingUpdatesCount() >= self::BIG_QUEUE_SIZE ) {
312 // If we cannot run the updates with outer transaction context, try to
313 // at least enqueue all the updates that support queueing to job queue
314 self::$preSendUpdates = self::enqueueUpdates( self::$preSendUpdates );
315 self::$postSendUpdates = self::enqueueUpdates( self::$postSendUpdates );
316 }
317
318 return !self::pendingUpdatesCount();
319 }
320
321 /**
322 * Enqueue a job for each EnqueueableDataUpdate item and return the other items
323 *
324 * @param DeferrableUpdate[] $updates A list of deferred update instances
325 * @return DeferrableUpdate[] Remaining updates that do not support being queued
326 */
327 private static function enqueueUpdates( array $updates ) {
328 $remaining = [];
329
330 foreach ( $updates as $update ) {
331 if ( $update instanceof EnqueueableDataUpdate ) {
332 $spec = $update->getAsJobSpecification();
333 JobQueueGroup::singleton( $spec['wiki'] )->push( $spec['job'] );
334 } else {
335 $remaining[] = $update;
336 }
337 }
338
339 return $remaining;
340 }
341
342 /**
343 * @return int Number of enqueued updates
344 * @since 1.28
345 */
346 public static function pendingUpdatesCount() {
347 return count( self::$preSendUpdates ) + count( self::$postSendUpdates );
348 }
349
350 /**
351 * @param int $stage DeferredUpdates constant (PRESEND, POSTSEND, or ALL)
352 * @return DeferrableUpdate[]
353 * @since 1.29
354 */
355 public static function getPendingUpdates( $stage = self::ALL ) {
356 $updates = [];
357 if ( $stage === self::ALL || $stage === self::PRESEND ) {
358 $updates = array_merge( $updates, self::$preSendUpdates );
359 }
360 if ( $stage === self::ALL || $stage === self::POSTSEND ) {
361 $updates = array_merge( $updates, self::$postSendUpdates );
362 }
363 return $updates;
364 }
365
366 /**
367 * Clear all pending updates without performing them. Generally, you don't
368 * want or need to call this. Unit tests need it though.
369 */
370 public static function clearPendingUpdates() {
371 self::$preSendUpdates = [];
372 self::$postSendUpdates = [];
373 }
374
375 /**
376 * @return bool If a transaction round is active or connection is not ready for commit()
377 */
378 private static function areDatabaseTransactionsActive() {
379 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
380 if ( $lbFactory->hasTransactionRound() || !$lbFactory->isReadyForRoundOperations() ) {
381 return true;
382 }
383
384 $connsBusy = false;
385 $lbFactory->forEachLB( function ( LoadBalancer $lb ) use ( &$connsBusy ) {
386 $lb->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$connsBusy ) {
387 if ( $conn->writesOrCallbacksPending() || $conn->explicitTrxActive() ) {
388 $connsBusy = true;
389 }
390 } );
391 } );
392
393 return $connsBusy;
394 }
395 }