3 * Generator and manager of database load balancing objects
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
24 namespace Wikimedia\Rdbms
;
26 use Psr\Log\LoggerInterface
;
27 use Psr\Log\NullLogger
;
28 use Wikimedia\ScopedCallback
;
37 * An interface for generating database load balancers
40 abstract class LBFactory
implements ILBFactory
{
41 /** @var ChronologyProtector */
43 /** @var object|string Class name or object With profileIn/profileOut methods */
45 /** @var TransactionProfiler */
47 /** @var LoggerInterface */
49 /** @var LoggerInterface */
51 /** @var LoggerInterface */
53 /** @var LoggerInterface */
55 /** @var callable Error logger */
57 /** @var callable Deprecation logger */
58 private $deprecationLogger;
64 /** @var WANObjectCache */
67 /** @var DatabaseDomain Local domain */
68 protected $localDomain;
70 /** @var string Local hostname of the app server */
72 /** @var array Web request information about the client */
74 /** @var bool Whether this PHP instance is for a CLI script */
76 /** @var string Agent name for query profiling */
78 /** @var string Secret string for HMAC hashing */
81 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
82 private $tableAliases = [];
83 /** @var string[] Map of (index alias => index) */
84 private $indexAliases = [];
85 /** @var callable[] */
86 private $replicationWaitCallbacks = [];
88 /** var int An identifier for this class instance */
90 /** @var int|null Ticket used to delegate transaction ownership */
92 /** @var string|bool String if a requested DBO_TRX transaction round is active */
93 private $trxRoundId = false;
94 /** @var string One of the ROUND_* class constants */
95 private $trxRoundStage = self
::ROUND_CURSORY
;
97 /** @var string|bool Reason all LBs are read-only or false if not */
98 protected $readOnlyReason = false;
100 /** @var string|null */
101 private $defaultGroup = null;
106 const ROUND_CURSORY
= 'cursory';
107 const ROUND_BEGINNING
= 'within-begin';
108 const ROUND_COMMITTING
= 'within-commit';
109 const ROUND_ROLLING_BACK
= 'within-rollback';
110 const ROUND_COMMIT_CALLBACKS
= 'within-commit-callbacks';
111 const ROUND_ROLLBACK_CALLBACKS
= 'within-rollback-callbacks';
113 private static $loggerFields =
114 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
116 public function __construct( array $conf ) {
117 $this->localDomain
= isset( $conf['localDomain'] )
118 ? DatabaseDomain
::newFromId( $conf['localDomain'] )
119 : DatabaseDomain
::newUnspecified();
121 $this->maxLag
= $conf['maxLag'] ??
null;
122 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
123 $this->readOnlyReason
= $conf['readOnlyReason'];
126 $this->srvCache
= $conf['srvCache'] ??
new EmptyBagOStuff();
127 $this->memStash
= $conf['memStash'] ??
new EmptyBagOStuff();
128 $this->wanCache
= $conf['wanCache'] ?? WANObjectCache
::newEmpty();
130 foreach ( self
::$loggerFields as $key ) {
131 $this->$key = $conf[$key] ??
new NullLogger();
133 $this->errorLogger
= $conf['errorLogger'] ??
function ( Exception
$e ) {
134 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
136 $this->deprecationLogger
= $conf['deprecationLogger'] ??
function ( $msg ) {
137 trigger_error( $msg, E_USER_DEPRECATED
);
140 $this->profiler
= $conf['profiler'] ??
null;
141 $this->trxProfiler
= $conf['trxProfiler'] ??
new TransactionProfiler();
143 $this->requestInfo
= [
144 'IPAddress' => $_SERVER[ 'REMOTE_ADDR' ] ??
'',
145 'UserAgent' => $_SERVER['HTTP_USER_AGENT'] ??
'',
146 // Headers application can inject via LBFactory::setRequestInfo()
147 'ChronologyProtection' => null,
148 'ChronologyClientId' => null, // prior $cpClientId value from LBFactory::shutdown()
149 'ChronologyPositionIndex' => null // prior $cpIndex value from LBFactory::shutdown()
152 $this->cliMode
= $conf['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
153 $this->hostname
= $conf['hostname'] ??
gethostname();
154 $this->agent
= $conf['agent'] ??
'';
155 $this->defaultGroup
= $conf['defaultGroup'] ??
null;
156 $this->secret
= $conf['secret'] ??
'';
158 $this->id
= mt_rand();
159 $this->ticket
= mt_rand();
162 public function destroy() {
163 $this->shutdown( self
::SHUTDOWN_NO_CHRONPROT
);
164 $this->forEachLBCallMethod( 'disable' );
167 public function getLocalDomainID() {
168 return $this->localDomain
->getId();
171 public function resolveDomainID( $domain ) {
172 return ( $domain !== false ) ?
(string)$domain : $this->getLocalDomainID();
175 public function shutdown(
176 $mode = self
::SHUTDOWN_CHRONPROT_SYNC
,
177 callable
$workCallback = null,
181 $chronProt = $this->getChronologyProtector();
182 if ( $mode === self
::SHUTDOWN_CHRONPROT_SYNC
) {
183 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
184 } elseif ( $mode === self
::SHUTDOWN_CHRONPROT_ASYNC
) {
185 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
188 $cpClientId = $chronProt->getClientId();
190 $this->commitMasterChanges( __METHOD__
); // sanity
194 * @see ILBFactory::newMainLB()
195 * @param bool $domain
196 * @return ILoadBalancer
198 abstract public function newMainLB( $domain = false );
201 * @see ILBFactory::getMainLB()
202 * @param bool $domain
203 * @return ILoadBalancer
205 abstract public function getMainLB( $domain = false );
208 * @see ILBFactory::newExternalLB()
209 * @param string $cluster
210 * @return ILoadBalancer
212 abstract public function newExternalLB( $cluster );
215 * @see ILBFactory::getExternalLB()
216 * @param string $cluster
217 * @return ILoadBalancer
219 abstract public function getExternalLB( $cluster );
222 * Call a method of each tracked load balancer
224 * @param string $methodName
227 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
229 function ( ILoadBalancer
$loadBalancer, $methodName, array $args ) {
230 $loadBalancer->$methodName( ...$args );
232 [ $methodName, $args ]
236 public function flushReplicaSnapshots( $fname = __METHOD__
) {
237 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
238 $this->queryLogger
->warning(
239 "$fname: transaction round '{$this->trxRoundId}' still running",
240 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
243 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
246 final public function commitAll( $fname = __METHOD__
, array $options = [] ) {
247 $this->commitMasterChanges( $fname, $options );
248 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
249 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
252 final public function beginMasterChanges( $fname = __METHOD__
) {
253 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
254 $this->trxRoundStage
= self
::ROUND_BEGINNING
;
255 if ( $this->trxRoundId
!== false ) {
256 throw new DBTransactionError(
258 "$fname: transaction round '{$this->trxRoundId}' already started"
261 $this->trxRoundId
= $fname;
262 // Set DBO_TRX flags on all appropriate DBs
263 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname, $this->id
] );
264 $this->trxRoundStage
= self
::ROUND_CURSORY
;
267 final public function commitMasterChanges( $fname = __METHOD__
, array $options = [] ) {
268 $this->assertTransactionRoundStage( self
::ROUND_CURSORY
);
269 $this->trxRoundStage
= self
::ROUND_COMMITTING
;
270 if ( $this->trxRoundId
!== false && $this->trxRoundId
!== $fname ) {
271 throw new DBTransactionError(
273 "$fname: transaction round '{$this->trxRoundId}' still running"
276 /** @noinspection PhpUnusedLocalVariableInspection */
277 $scope = ScopedCallback
::newScopedIgnoreUserAbort(); // try to ignore client aborts
278 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
280 $count = 0; // number of callbacks executed this iteration
281 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$count, $fname ) {
282 $count +
= $lb->finalizeMasterChanges( $fname, $this->id
);
284 } while ( $count > 0 );
285 $this->trxRoundId
= false;
286 // Perform pre-commit checks, aborting on failure
287 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options, $fname, $this->id
] );
288 // Log the DBs and methods involved in multi-DB transactions
289 $this->logIfMultiDbTransaction();
290 // Actually perform the commit on all master DB connections and revert DBO_TRX
291 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname, $this->id
] );
292 // Run all post-commit callbacks in a separate step
293 $this->trxRoundStage
= self
::ROUND_COMMIT_CALLBACKS
;
294 $e = $this->executePostTransactionCallbacks();
295 $this->trxRoundStage
= self
::ROUND_CURSORY
;
296 // Throw any last post-commit callback error
297 if ( $e instanceof Exception
) {
302 final public function rollbackMasterChanges( $fname = __METHOD__
) {
303 $this->trxRoundStage
= self
::ROUND_ROLLING_BACK
;
304 $this->trxRoundId
= false;
305 // Actually perform the rollback on all master DB connections and revert DBO_TRX
306 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname, $this->id
] );
307 // Run all post-commit callbacks in a separate step
308 $this->trxRoundStage
= self
::ROUND_ROLLBACK_CALLBACKS
;
309 $this->executePostTransactionCallbacks();
310 $this->trxRoundStage
= self
::ROUND_CURSORY
;
314 * @return Exception|null
316 private function executePostTransactionCallbacks() {
318 // Run all post-commit callbacks until new ones stop getting added
319 $e = null; // first callback exception
321 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e, $fname ) {
322 $ex = $lb->runMasterTransactionIdleCallbacks( $fname, $this->id
);
325 } while ( $this->hasMasterChanges() );
326 // Run all listener callbacks once
327 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$e, $fname ) {
328 $ex = $lb->runMasterTransactionListenerCallbacks( $fname, $this->id
);
335 public function hasTransactionRound() {
336 return ( $this->trxRoundId
!== false );
339 public function isReadyForRoundOperations() {
340 return ( $this->trxRoundStage
=== self
::ROUND_CURSORY
);
344 * Log query info if multi DB transactions are going to be committed now
346 private function logIfMultiDbTransaction() {
348 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$callersByDB ) {
349 $masterName = $lb->getServerName( $lb->getWriterIndex() );
350 $callers = $lb->pendingMasterChangeCallers();
352 $callersByDB[$masterName] = $callers;
356 if ( count( $callersByDB ) >= 2 ) {
357 $dbs = implode( ', ', array_keys( $callersByDB ) );
358 $msg = "Multi-DB transaction [{$dbs}]:\n";
359 foreach ( $callersByDB as $db => $callers ) {
360 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
362 $this->queryLogger
->info( $msg );
366 public function hasMasterChanges() {
368 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
369 $ret = $ret ||
$lb->hasMasterChanges();
375 public function laggedReplicaUsed() {
377 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$ret ) {
378 $ret = $ret ||
$lb->laggedReplicaUsed();
384 public function hasOrMadeRecentMasterChanges( $age = null ) {
386 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $age, &$ret ) {
387 $ret = $ret ||
$lb->hasOrMadeRecentMasterChanges( $age );
392 public function waitForReplication( array $opts = [] ) {
396 'timeout' => $this->cliMode ?
60 : 1,
397 'ifWritesSince' => null
400 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
401 $opts['domain'] = $opts['wiki']; // b/c
404 // Figure out which clusters need to be checked
405 /** @var ILoadBalancer[] $lbs */
407 if ( $opts['cluster'] !== false ) {
408 $lbs[] = $this->getExternalLB( $opts['cluster'] );
409 } elseif ( $opts['domain'] !== false ) {
410 $lbs[] = $this->getMainLB( $opts['domain'] );
412 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$lbs ) {
416 return true; // nothing actually used
420 // Get all the master positions of applicable DBs right now.
421 // This can be faster since waiting on one cluster reduces the
422 // time needed to wait on the next clusters.
423 $masterPositions = array_fill( 0, count( $lbs ), false );
424 foreach ( $lbs as $i => $lb ) {
425 if ( !$lb->hasStreamingReplicaServers() ) {
426 continue; // T29975: no replication; avoid getMasterPos() permissions errors
428 $opts['ifWritesSince'] &&
429 $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
431 continue; // no writes since the last wait
433 $masterPositions[$i] = $lb->getMasterPos();
436 // Run any listener callbacks *after* getting the DB positions. The more
437 // time spent in the callbacks, the less time is spent in waitForAll().
438 foreach ( $this->replicationWaitCallbacks
as $callback ) {
443 foreach ( $lbs as $i => $lb ) {
444 if ( $masterPositions[$i] ) {
445 // The RDBMS may not support getMasterPos()
446 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
447 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
455 public function setWaitForReplicationListener( $name, callable
$callback = null ) {
457 $this->replicationWaitCallbacks
[$name] = $callback;
459 unset( $this->replicationWaitCallbacks
[$name] );
463 public function getEmptyTransactionTicket( $fname ) {
464 if ( $this->hasMasterChanges() ) {
465 $this->queryLogger
->error(
466 __METHOD__
. ": $fname does not have outer scope",
467 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
473 return $this->ticket
;
476 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
477 if ( $ticket !== $this->ticket
) {
478 $this->perfLogger
->error(
479 __METHOD__
. ": $fname does not have outer scope",
480 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
486 // The transaction owner and any caller with the empty transaction ticket can commit
487 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
488 if ( $this->trxRoundId
!== false && $fname !== $this->trxRoundId
) {
489 $this->queryLogger
->info( "$fname: committing on behalf of {$this->trxRoundId}" );
490 $fnameEffective = $this->trxRoundId
;
492 $fnameEffective = $fname;
495 $this->commitMasterChanges( $fnameEffective );
496 $waitSucceeded = $this->waitForReplication( $opts );
497 // If a nested caller committed on behalf of $fname, start another empty $fname
498 // transaction, leaving the caller with the same empty transaction state as before.
499 if ( $fnameEffective !== $fname ) {
500 $this->beginMasterChanges( $fnameEffective );
503 return $waitSucceeded;
506 public function getChronologyProtectorTouched( $dbName ) {
507 return $this->getChronologyProtector()->getTouched( $dbName );
510 public function disableChronologyProtection() {
511 $this->getChronologyProtector()->setEnabled( false );
515 * @return ChronologyProtector
517 protected function getChronologyProtector() {
518 if ( $this->chronProt
) {
519 return $this->chronProt
;
522 $this->chronProt
= new ChronologyProtector(
525 'ip' => $this->requestInfo
['IPAddress'],
526 'agent' => $this->requestInfo
['UserAgent'],
527 'clientId' => $this->requestInfo
['ChronologyClientId'] ?
: null
529 $this->requestInfo
['ChronologyPositionIndex'],
532 $this->chronProt
->setLogger( $this->replLogger
);
534 if ( $this->cliMode
) {
535 $this->chronProt
->setEnabled( false );
536 } elseif ( $this->requestInfo
['ChronologyProtection'] === 'false' ) {
537 // Request opted out of using position wait logic. This is useful for requests
538 // done by the job queue or background ETL that do not have a meaningful session.
539 $this->chronProt
->setWaitEnabled( false );
540 } elseif ( $this->memStash
instanceof EmptyBagOStuff
) {
541 // No where to store any DB positions and wait for them to appear
542 $this->chronProt
->setEnabled( false );
543 $this->replLogger
->info( 'Cannot use ChronologyProtector with EmptyBagOStuff' );
546 $this->replLogger
->debug(
547 __METHOD__
. ': request info ' .
548 json_encode( $this->requestInfo
, JSON_PRETTY_PRINT
)
551 return $this->chronProt
;
555 * Get and record all of the staged DB positions into persistent memory storage
557 * @param ChronologyProtector $cp
558 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
559 * @param string $mode One of (sync, async); whether to wait on remote datacenters
560 * @param int|null &$cpIndex DB position key write counter; incremented on update
562 protected function shutdownChronologyProtector(
563 ChronologyProtector
$cp, $workCallback, $mode, &$cpIndex = null
565 // Record all the master positions needed
566 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $cp ) {
567 $cp->storeSessionReplicationPosition( $lb );
569 // Write them to the persistent stash. Try to do something useful by running $work
570 // while ChronologyProtector waits for the stash write to replicate to all DCs.
571 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
572 if ( $unsavedPositions && $workCallback ) {
573 // Invoke callback in case it did not cache the result yet
574 $workCallback(); // work now to block for less time in waitForAll()
576 // If the positions failed to write to the stash, at least wait on local datacenter
577 // replica DBs to catch up before responding. Even if there are several DCs, this increases
578 // the chance that the user will see their own changes immediately afterwards. As long
579 // as the sticky DC cookie applies (same domain), this is not even an issue.
580 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $unsavedPositions ) {
581 $masterName = $lb->getServerName( $lb->getWriterIndex() );
582 if ( isset( $unsavedPositions[$masterName] ) ) {
583 $lb->waitForAll( $unsavedPositions[$masterName] );
589 * Base parameters to ILoadBalancer::__construct()
592 final protected function baseLoadBalancerParams() {
593 if ( $this->trxRoundStage
=== self
::ROUND_COMMIT_CALLBACKS
) {
594 $initStage = ILoadBalancer
::STAGE_POSTCOMMIT_CALLBACKS
;
595 } elseif ( $this->trxRoundStage
=== self
::ROUND_ROLLBACK_CALLBACKS
) {
596 $initStage = ILoadBalancer
::STAGE_POSTROLLBACK_CALLBACKS
;
602 'localDomain' => $this->localDomain
,
603 'readOnlyReason' => $this->readOnlyReason
,
604 'srvCache' => $this->srvCache
,
605 'wanCache' => $this->wanCache
,
606 'profiler' => $this->profiler
,
607 'trxProfiler' => $this->trxProfiler
,
608 'queryLogger' => $this->queryLogger
,
609 'connLogger' => $this->connLogger
,
610 'replLogger' => $this->replLogger
,
611 'errorLogger' => $this->errorLogger
,
612 'deprecationLogger' => $this->deprecationLogger
,
613 'hostname' => $this->hostname
,
614 'cliMode' => $this->cliMode
,
615 'agent' => $this->agent
,
616 'maxLag' => $this->maxLag
,
617 'defaultGroup' => $this->defaultGroup
,
618 'chronologyCallback' => function ( ILoadBalancer
$lb ) {
619 // Defer ChronologyProtector construction in case setRequestInfo() ends up
620 // being called later (but before the first connection attempt) (T192611)
621 $this->getChronologyProtector()->applySessionReplicationPosition( $lb );
623 'roundStage' => $initStage,
624 'ownerId' => $this->id
629 * @param ILoadBalancer $lb
631 protected function initLoadBalancer( ILoadBalancer
$lb ) {
632 if ( $this->trxRoundId
!== false ) {
633 $lb->beginMasterChanges( $this->trxRoundId
, $this->id
); // set DBO_TRX
636 $lb->setTableAliases( $this->tableAliases
);
637 $lb->setIndexAliases( $this->indexAliases
);
640 public function setTableAliases( array $aliases ) {
641 $this->tableAliases
= $aliases;
644 public function setIndexAliases( array $aliases ) {
645 $this->indexAliases
= $aliases;
649 * @param string $prefix
650 * @deprecated Since 1.33
652 public function setDomainPrefix( $prefix ) {
653 $this->setLocalDomainPrefix( $prefix );
656 public function setLocalDomainPrefix( $prefix ) {
657 $this->localDomain
= new DatabaseDomain(
658 $this->localDomain
->getDatabase(),
659 $this->localDomain
->getSchema(),
663 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( $prefix ) {
664 $lb->setLocalDomainPrefix( $prefix );
668 public function redefineLocalDomain( $domain ) {
671 $this->localDomain
= DatabaseDomain
::newFromId( $domain );
673 $this->forEachLB( function ( ILoadBalancer
$lb ) {
674 $lb->redefineLocalDomain( $this->localDomain
);
678 public function closeAll() {
679 $this->forEachLBCallMethod( 'closeAll' );
682 public function setAgentName( $agent ) {
683 $this->agent
= $agent;
686 public function appendShutdownCPIndexAsQuery( $url, $index ) {
688 $this->forEachLB( function ( ILoadBalancer
$lb ) use ( &$usedCluster ) {
689 $usedCluster |
= $lb->hasStreamingReplicaServers();
692 if ( !$usedCluster ) {
693 return $url; // no master/replica clusters touched
696 return strpos( $url, '?' ) === false ?
"$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
699 public function getChronologyProtectorClientId() {
700 return $this->getChronologyProtector()->getClientId();
704 * @param int $index Write index
705 * @param int $time UNIX timestamp; can be used to detect stale cookies (T190082)
706 * @param string $clientId Agent ID hash from ILBFactory::shutdown()
707 * @return string Timestamp-qualified write index of the form "<index>@<timestamp>#<hash>"
710 public static function makeCookieValueFromCPIndex( $index, $time, $clientId ) {
711 return "$index@$time#$clientId";
715 * @param string $value Possible result of LBFactory::makeCookieValueFromCPIndex()
716 * @param int $minTimestamp Lowest UNIX timestamp that a non-expired value can have
717 * @return array (index: int or null, clientId: string or null)
720 public static function getCPInfoFromCookieValue( $value, $minTimestamp ) {
721 static $placeholder = [ 'index' => null, 'clientId' => null ];
723 if ( !preg_match( '/^(\d+)@(\d+)#([0-9a-f]{32})$/', $value, $m ) ) {
724 return $placeholder; // invalid
729 return $placeholder; // invalid
730 } elseif ( isset( $m[2] ) && $m[2] !== '' && (int)$m[2] < $minTimestamp ) {
731 return $placeholder; // expired
734 $clientId = ( isset( $m[3] ) && $m[3] !== '' ) ?
$m[3] : null;
736 return [ 'index' => $index, 'clientId' => $clientId ];
739 public function setRequestInfo( array $info ) {
740 if ( $this->chronProt
) {
741 throw new LogicException( 'ChronologyProtector already initialized' );
744 $this->requestInfo
= $info +
$this->requestInfo
;
748 * @param string $stage
750 private function assertTransactionRoundStage( $stage ) {
751 if ( $this->trxRoundStage
!== $stage ) {
752 throw new DBTransactionError(
754 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
759 function __destruct() {