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