Merge "rdbms: consolidate LBFactory code for running callbacks"
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / LBFactory.php
1 <?php
2 /**
3 * Generator and manager of database load balancing objects
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 * @ingroup Database
22 */
23
24 namespace Wikimedia\Rdbms;
25
26 use Psr\Log\LoggerInterface;
27 use Wikimedia\ScopedCallback;
28 use BagOStuff;
29 use EmptyBagOStuff;
30 use WANObjectCache;
31 use Exception;
32 use RuntimeException;
33 use LogicException;
34
35 /**
36 * An interface for generating database load balancers
37 * @ingroup Database
38 */
39 abstract class LBFactory implements ILBFactory {
40 /** @var ChronologyProtector */
41 protected $chronProt;
42 /** @var object|string Class name or object With profileIn/profileOut methods */
43 protected $profiler;
44 /** @var TransactionProfiler */
45 protected $trxProfiler;
46 /** @var LoggerInterface */
47 protected $replLogger;
48 /** @var LoggerInterface */
49 protected $connLogger;
50 /** @var LoggerInterface */
51 protected $queryLogger;
52 /** @var LoggerInterface */
53 protected $perfLogger;
54 /** @var callable Error logger */
55 protected $errorLogger;
56 /** @var callable Deprecation logger */
57 protected $deprecationLogger;
58 /** @var BagOStuff */
59 protected $srvCache;
60 /** @var BagOStuff */
61 protected $memStash;
62 /** @var WANObjectCache */
63 protected $wanCache;
64
65 /** @var DatabaseDomain Local domain */
66 protected $localDomain;
67 /** @var string Local hostname of the app server */
68 protected $hostname;
69 /** @var array Web request information about the client */
70 protected $requestInfo;
71
72 /** @var mixed */
73 protected $ticket;
74 /** @var string|bool String if a requested DBO_TRX transaction round is active */
75 protected $trxRoundId = false;
76 /** @var string|bool Reason all LBs are read-only or false if not */
77 protected $readOnlyReason = false;
78 /** @var callable[] */
79 protected $replicationWaitCallbacks = [];
80
81 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
82 protected $tableAliases = [];
83 /** @var string[] Map of (index alias => index) */
84 protected $indexAliases = [];
85
86 /** @var bool Whether this PHP instance is for a CLI script */
87 protected $cliMode;
88 /** @var string Agent name for query profiling */
89 protected $agent;
90
91 /** @var string One of the ROUND_* class constants */
92 private $trxRoundStage = self::ROUND_CURSORY;
93
94 const ROUND_CURSORY = 'cursory';
95 const ROUND_BEGINNING = 'within-begin';
96 const ROUND_COMMITTING = 'within-commit';
97 const ROUND_ROLLING_BACK = 'within-rollback';
98
99 private static $loggerFields =
100 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
101
102 public function __construct( array $conf ) {
103 $this->localDomain = isset( $conf['localDomain'] )
104 ? DatabaseDomain::newFromId( $conf['localDomain'] )
105 : DatabaseDomain::newUnspecified();
106
107 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
108 $this->readOnlyReason = $conf['readOnlyReason'];
109 }
110
111 $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff();
112 $this->memStash = isset( $conf['memStash'] ) ? $conf['memStash'] : new EmptyBagOStuff();
113 $this->wanCache = isset( $conf['wanCache'] )
114 ? $conf['wanCache']
115 : WANObjectCache::newEmpty();
116
117 foreach ( self::$loggerFields as $key ) {
118 $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger();
119 }
120 $this->errorLogger = isset( $conf['errorLogger'] )
121 ? $conf['errorLogger']
122 : function ( Exception $e ) {
123 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
124 };
125 $this->deprecationLogger = isset( $conf['deprecationLogger'] )
126 ? $conf['deprecationLogger']
127 : function ( $msg ) {
128 trigger_error( $msg, E_USER_DEPRECATED );
129 };
130
131 $this->profiler = isset( $conf['profiler'] ) ? $conf['profiler'] : null;
132 $this->trxProfiler = isset( $conf['trxProfiler'] )
133 ? $conf['trxProfiler']
134 : new TransactionProfiler();
135
136 $this->requestInfo = [
137 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '',
138 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '',
139 'ChronologyProtection' => 'true',
140 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ? $_GET['cpPosIndex'] : null
141 ];
142
143 $this->cliMode = isset( $conf['cliMode'] )
144 ? $conf['cliMode']
145 : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
146 $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname();
147 $this->agent = isset( $conf['agent'] ) ? $conf['agent'] : '';
148
149 $this->ticket = mt_rand();
150 }
151
152 public function destroy() {
153 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
154 $this->forEachLBCallMethod( 'disable' );
155 }
156
157 public function shutdown(
158 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null, &$cpIndex = null
159 ) {
160 $chronProt = $this->getChronologyProtector();
161 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
162 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
163 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
164 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
165 }
166
167 $this->commitMasterChanges( __METHOD__ ); // sanity
168 }
169
170 /**
171 * @see ILBFactory::newMainLB()
172 * @param bool $domain
173 * @return LoadBalancer
174 */
175 abstract public function newMainLB( $domain = false );
176
177 /**
178 * @see ILBFactory::getMainLB()
179 * @param bool $domain
180 * @return LoadBalancer
181 */
182 abstract public function getMainLB( $domain = false );
183
184 /**
185 * @see ILBFactory::newExternalLB()
186 * @param string $cluster
187 * @return LoadBalancer
188 */
189 abstract public function newExternalLB( $cluster );
190
191 /**
192 * @see ILBFactory::getExternalLB()
193 * @param string $cluster
194 * @return LoadBalancer
195 */
196 abstract public function getExternalLB( $cluster );
197
198 /**
199 * Call a method of each tracked load balancer
200 *
201 * @param string $methodName
202 * @param array $args
203 */
204 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
205 $this->forEachLB(
206 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
207 call_user_func_array( [ $loadBalancer, $methodName ], $args );
208 },
209 [ $methodName, $args ]
210 );
211 }
212
213 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
214 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
215 }
216
217 final public function commitAll( $fname = __METHOD__, array $options = [] ) {
218 $this->commitMasterChanges( $fname, $options );
219 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
220 }
221
222 final public function beginMasterChanges( $fname = __METHOD__ ) {
223 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
224 $this->trxRoundStage = self::ROUND_BEGINNING;
225 if ( $this->trxRoundId !== false ) {
226 throw new DBTransactionError(
227 null,
228 "$fname: transaction round '{$this->trxRoundId}' already started."
229 );
230 }
231 $this->trxRoundId = $fname;
232 // Set DBO_TRX flags on all appropriate DBs
233 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
234 $this->trxRoundStage = self::ROUND_CURSORY;
235 }
236
237 final public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
238 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
239 $this->trxRoundStage = self::ROUND_COMMITTING;
240 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
241 throw new DBTransactionError(
242 null,
243 "$fname: transaction round '{$this->trxRoundId}' still running."
244 );
245 }
246 /** @noinspection PhpUnusedLocalVariableInspection */
247 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
248 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
249 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
250 $this->trxRoundId = false;
251 // Perform pre-commit checks, aborting on failure
252 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
253 // Log the DBs and methods involved in multi-DB transactions
254 $this->logIfMultiDbTransaction();
255 // Actually perform the commit on all master DB connections and revert DBO_TRX
256 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
257 // Run all post-commit callbacks in a separate step
258 $e = $this->executePostTransactionCallbacks();
259 $this->trxRoundStage = self::ROUND_CURSORY;
260 // Throw any last post-commit callback error
261 if ( $e instanceof Exception ) {
262 throw $e;
263 }
264 }
265
266 final public function rollbackMasterChanges( $fname = __METHOD__ ) {
267 $this->trxRoundStage = self::ROUND_ROLLING_BACK;
268 $this->trxRoundId = false;
269 // Actually perform the rollback on all master DB connections and revert DBO_TRX
270 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
271 // Run all post-commit callbacks in a separate step
272 $this->executePostTransactionCallbacks();
273 $this->trxRoundStage = self::ROUND_CURSORY;
274 }
275
276 /**
277 * @return Exception|null
278 */
279 private function executePostTransactionCallbacks() {
280 // Run all post-commit callbacks until new ones stop getting added
281 $e = null; // first callback exception
282 do {
283 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
284 $ex = $lb->runMasterTransactionIdleCallbacks();
285 $e = $e ?: $ex;
286 } );
287 } while ( $this->hasMasterChanges() );
288 // Run all listener callbacks once
289 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
290 $ex = $lb->runMasterTransactionListenerCallbacks();
291 $e = $e ?: $ex;
292 } );
293
294 return $e;
295 }
296
297 public function hasTransactionRound() {
298 return ( $this->trxRoundId !== false );
299 }
300
301 public function isReadyForRoundOperations() {
302 return ( $this->trxRoundStage === self::ROUND_CURSORY );
303 }
304
305 /**
306 * Log query info if multi DB transactions are going to be committed now
307 */
308 private function logIfMultiDbTransaction() {
309 $callersByDB = [];
310 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
311 $masterName = $lb->getServerName( $lb->getWriterIndex() );
312 $callers = $lb->pendingMasterChangeCallers();
313 if ( $callers ) {
314 $callersByDB[$masterName] = $callers;
315 }
316 } );
317
318 if ( count( $callersByDB ) >= 2 ) {
319 $dbs = implode( ', ', array_keys( $callersByDB ) );
320 $msg = "Multi-DB transaction [{$dbs}]:\n";
321 foreach ( $callersByDB as $db => $callers ) {
322 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
323 }
324 $this->queryLogger->info( $msg );
325 }
326 }
327
328 public function hasMasterChanges() {
329 $ret = false;
330 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
331 $ret = $ret || $lb->hasMasterChanges();
332 } );
333
334 return $ret;
335 }
336
337 public function laggedReplicaUsed() {
338 $ret = false;
339 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
340 $ret = $ret || $lb->laggedReplicaUsed();
341 } );
342
343 return $ret;
344 }
345
346 public function hasOrMadeRecentMasterChanges( $age = null ) {
347 $ret = false;
348 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
349 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
350 } );
351 return $ret;
352 }
353
354 public function waitForReplication( array $opts = [] ) {
355 $opts += [
356 'domain' => false,
357 'cluster' => false,
358 'timeout' => $this->cliMode ? 60 : 10,
359 'ifWritesSince' => null
360 ];
361
362 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
363 $opts['domain'] = $opts['wiki']; // b/c
364 }
365
366 // Figure out which clusters need to be checked
367 /** @var ILoadBalancer[] $lbs */
368 $lbs = [];
369 if ( $opts['cluster'] !== false ) {
370 $lbs[] = $this->getExternalLB( $opts['cluster'] );
371 } elseif ( $opts['domain'] !== false ) {
372 $lbs[] = $this->getMainLB( $opts['domain'] );
373 } else {
374 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
375 $lbs[] = $lb;
376 } );
377 if ( !$lbs ) {
378 return; // nothing actually used
379 }
380 }
381
382 // Get all the master positions of applicable DBs right now.
383 // This can be faster since waiting on one cluster reduces the
384 // time needed to wait on the next clusters.
385 $masterPositions = array_fill( 0, count( $lbs ), false );
386 foreach ( $lbs as $i => $lb ) {
387 if ( $lb->getServerCount() <= 1 ) {
388 // T29975 - Don't try to wait for replica DBs if there are none
389 // Prevents permission error when getting master position
390 continue;
391 } elseif ( $opts['ifWritesSince']
392 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
393 ) {
394 continue; // no writes since the last wait
395 }
396 $masterPositions[$i] = $lb->getMasterPos();
397 }
398
399 // Run any listener callbacks *after* getting the DB positions. The more
400 // time spent in the callbacks, the less time is spent in waitForAll().
401 foreach ( $this->replicationWaitCallbacks as $callback ) {
402 $callback();
403 }
404
405 $failed = [];
406 foreach ( $lbs as $i => $lb ) {
407 if ( $masterPositions[$i] ) {
408 // The RDBMS may not support getMasterPos()
409 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
410 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
411 }
412 }
413 }
414
415 if ( $failed ) {
416 throw new DBReplicationWaitError(
417 null,
418 "Could not wait for replica DBs to catch up to " .
419 implode( ', ', $failed )
420 );
421 }
422 }
423
424 public function setWaitForReplicationListener( $name, callable $callback = null ) {
425 if ( $callback ) {
426 $this->replicationWaitCallbacks[$name] = $callback;
427 } else {
428 unset( $this->replicationWaitCallbacks[$name] );
429 }
430 }
431
432 public function getEmptyTransactionTicket( $fname ) {
433 if ( $this->hasMasterChanges() ) {
434 $this->queryLogger->error( __METHOD__ . ": $fname does not have outer scope.\n" .
435 ( new RuntimeException() )->getTraceAsString() );
436
437 return null;
438 }
439
440 return $this->ticket;
441 }
442
443 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
444 if ( $ticket !== $this->ticket ) {
445 $this->perfLogger->error( __METHOD__ . ": $fname does not have outer scope.\n" .
446 ( new RuntimeException() )->getTraceAsString() );
447
448 return;
449 }
450
451 // The transaction owner and any caller with the empty transaction ticket can commit
452 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
453 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
454 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
455 $fnameEffective = $this->trxRoundId;
456 } else {
457 $fnameEffective = $fname;
458 }
459
460 $this->commitMasterChanges( $fnameEffective );
461 $this->waitForReplication( $opts );
462 // If a nested caller committed on behalf of $fname, start another empty $fname
463 // transaction, leaving the caller with the same empty transaction state as before.
464 if ( $fnameEffective !== $fname ) {
465 $this->beginMasterChanges( $fnameEffective );
466 }
467 }
468
469 public function getChronologyProtectorTouched( $dbName ) {
470 return $this->getChronologyProtector()->getTouched( $dbName );
471 }
472
473 public function disableChronologyProtection() {
474 $this->getChronologyProtector()->setEnabled( false );
475 }
476
477 /**
478 * @return ChronologyProtector
479 */
480 protected function getChronologyProtector() {
481 if ( $this->chronProt ) {
482 return $this->chronProt;
483 }
484
485 $this->chronProt = new ChronologyProtector(
486 $this->memStash,
487 [
488 'ip' => $this->requestInfo['IPAddress'],
489 'agent' => $this->requestInfo['UserAgent'],
490 ],
491 $this->requestInfo['ChronologyPositionIndex']
492 );
493 $this->chronProt->setLogger( $this->replLogger );
494
495 if ( $this->cliMode ) {
496 $this->chronProt->setEnabled( false );
497 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
498 // Request opted out of using position wait logic. This is useful for requests
499 // done by the job queue or background ETL that do not have a meaningful session.
500 $this->chronProt->setWaitEnabled( false );
501 }
502
503 $this->replLogger->debug( __METHOD__ . ': using request info ' .
504 json_encode( $this->requestInfo, JSON_PRETTY_PRINT ) );
505
506 return $this->chronProt;
507 }
508
509 /**
510 * Get and record all of the staged DB positions into persistent memory storage
511 *
512 * @param ChronologyProtector $cp
513 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
514 * @param string $mode One of (sync, async); whether to wait on remote datacenters
515 * @param int|null &$cpIndex DB position key write counter; incremented on update
516 */
517 protected function shutdownChronologyProtector(
518 ChronologyProtector $cp, $workCallback, $mode, &$cpIndex = null
519 ) {
520 // Record all the master positions needed
521 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
522 $cp->shutdownLB( $lb );
523 } );
524 // Write them to the persistent stash. Try to do something useful by running $work
525 // while ChronologyProtector waits for the stash write to replicate to all DCs.
526 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
527 if ( $unsavedPositions && $workCallback ) {
528 // Invoke callback in case it did not cache the result yet
529 $workCallback(); // work now to block for less time in waitForAll()
530 }
531 // If the positions failed to write to the stash, at least wait on local datacenter
532 // replica DBs to catch up before responding. Even if there are several DCs, this increases
533 // the chance that the user will see their own changes immediately afterwards. As long
534 // as the sticky DC cookie applies (same domain), this is not even an issue.
535 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
536 $masterName = $lb->getServerName( $lb->getWriterIndex() );
537 if ( isset( $unsavedPositions[$masterName] ) ) {
538 $lb->waitForAll( $unsavedPositions[$masterName] );
539 }
540 } );
541 }
542
543 /**
544 * Base parameters to LoadBalancer::__construct()
545 * @return array
546 */
547 final protected function baseLoadBalancerParams() {
548 return [
549 'localDomain' => $this->localDomain,
550 'readOnlyReason' => $this->readOnlyReason,
551 'srvCache' => $this->srvCache,
552 'wanCache' => $this->wanCache,
553 'profiler' => $this->profiler,
554 'trxProfiler' => $this->trxProfiler,
555 'queryLogger' => $this->queryLogger,
556 'connLogger' => $this->connLogger,
557 'replLogger' => $this->replLogger,
558 'errorLogger' => $this->errorLogger,
559 'deprecationLogger' => $this->deprecationLogger,
560 'hostname' => $this->hostname,
561 'cliMode' => $this->cliMode,
562 'agent' => $this->agent,
563 'chronologyCallback' => function ( ILoadBalancer $lb ) {
564 // Defer ChronologyProtector construction in case setRequestInfo() ends up
565 // being called later (but before the first connection attempt) (T192611)
566 $this->getChronologyProtector()->initLB( $lb );
567 }
568 ];
569 }
570
571 /**
572 * @param ILoadBalancer $lb
573 */
574 protected function initLoadBalancer( ILoadBalancer $lb ) {
575 if ( $this->trxRoundId !== false ) {
576 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
577 }
578
579 $lb->setTableAliases( $this->tableAliases );
580 $lb->setIndexAliases( $this->indexAliases );
581 }
582
583 public function setTableAliases( array $aliases ) {
584 $this->tableAliases = $aliases;
585 }
586
587 public function setIndexAliases( array $aliases ) {
588 $this->indexAliases = $aliases;
589 }
590
591 public function setDomainPrefix( $prefix ) {
592 $this->localDomain = new DatabaseDomain(
593 $this->localDomain->getDatabase(),
594 null,
595 $prefix
596 );
597
598 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $prefix ) {
599 $lb->setDomainPrefix( $prefix );
600 } );
601 }
602
603 public function closeAll() {
604 $this->forEachLBCallMethod( 'closeAll', [] );
605 }
606
607 public function setAgentName( $agent ) {
608 $this->agent = $agent;
609 }
610
611 public function appendShutdownCPIndexAsQuery( $url, $index ) {
612 $usedCluster = 0;
613 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
614 $usedCluster |= ( $lb->getServerCount() > 1 );
615 } );
616
617 if ( !$usedCluster ) {
618 return $url; // no master/replica clusters touched
619 }
620
621 return strpos( $url, '?' ) === false ? "$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
622 }
623
624 public function setRequestInfo( array $info ) {
625 if ( $this->chronProt ) {
626 throw new LogicException( 'ChronologyProtector already initialized.' );
627 }
628
629 $this->requestInfo = $info + $this->requestInfo;
630 }
631
632 /**
633 * @param string $stage
634 */
635 private function assertTransactionRoundStage( $stage ) {
636 if ( $this->trxRoundStage !== $stage ) {
637 throw new DBTransactionError(
638 null,
639 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
640 );
641 }
642 }
643
644 /**
645 * Make PHP ignore user aborts/disconnects until the returned
646 * value leaves scope. This returns null and does nothing in CLI mode.
647 *
648 * @return ScopedCallback|null
649 */
650 final protected function getScopedPHPBehaviorForCommit() {
651 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
652 $old = ignore_user_abort( true ); // avoid half-finished operations
653 return new ScopedCallback( function () use ( $old ) {
654 ignore_user_abort( $old );
655 } );
656 }
657
658 return null;
659 }
660
661 function __destruct() {
662 $this->destroy();
663 }
664 }
665
666 class_alias( LBFactory::class, 'LBFactory' );