Debian Codegraph @

includes/objectcache/SqlBagOStuff.php

raw symbols SCIP
1 <?php
2 /**
3 * Object caching using a SQL database.
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 Cache
22 */
23
24 use MediaWiki\MediaWikiServices;
25 use Wikimedia\AtEase\AtEase;
26 use Wikimedia\ObjectCache\MediumSpecificBagOStuff;
27 use Wikimedia\Rdbms\Blob;
28 use Wikimedia\Rdbms\Database;
29 use Wikimedia\Rdbms\DBConnectionError;
30 use Wikimedia\Rdbms\DBError;
31 use Wikimedia\Rdbms\DBQueryError;
32 use Wikimedia\Rdbms\IDatabase;
33 use Wikimedia\Rdbms\ILoadBalancer;
34 use Wikimedia\Rdbms\IMaintainableDatabase;
35 use Wikimedia\Rdbms\RawSQLValue;
36 use Wikimedia\Rdbms\SelectQueryBuilder;
37 use Wikimedia\Rdbms\ServerInfo;
38 use Wikimedia\ScopedCallback;
39 use Wikimedia\Timestamp\ConvertibleTimestamp;
40
41 /**
42 * RDBMS-based caching module
43 *
44 * The following database sharding schemes are supported:
45 * - None; all keys map to the same shard
46 * - Hash; keys map to shards via consistent hashing
47 *
48 * The following database replication topologies are supported:
49 * - A primary database server for each shard, all within one datacenter
50 * - A co-primary database server for each shard within each datacenter
51 *
52 * @ingroup Cache
53 */
54 class SqlBagOStuff extends MediumSpecificBagOStuff {
55 /** @var callable|null Injected function which returns a LoadBalancer */
56 protected $loadBalancerCallback;
57 /** @var ILoadBalancer|null */
58 protected $loadBalancer;
59 /** @var string|false|null DB name used for keys using the LoadBalancer */
60 protected $dbDomain;
61 /** @var bool Whether to use the LoadBalancer */
62 protected $useLB = false;
63
64 /** @var array[] (server index => server config) */
65 protected $serverInfos = [];
66 /** @var string[] (server index => tag/host name) */
67 protected $serverTags = [];
68 /** @var float UNIX timestamp */
69 protected $lastGarbageCollect = 0;
70 /** @var int Average number of writes required to trigger garbage collection */
71 protected $purgePeriod = 10;
72 /** @var int Max expired rows to purge during randomized garbage collection */
73 protected $purgeLimit = 100;
74 /** @var int Number of table shards to use on each server */
75 protected $numTableShards = 1;
76 /** @var int */
77 protected $writeBatchSize = 100;
78 /** @var string */
79 protected $tableName = 'objectcache';
80 /** @var bool Whether multi-primary mode is enabled */
81 protected $multiPrimaryMode;
82
83 /** @var IMaintainableDatabase[] Map of (shard index => DB handle) */
84 protected $conns;
85 /** @var float[] Map of (shard index => UNIX timestamps) */
86 protected $connFailureTimes = [];
87 /** @var Exception[] Map of (shard index => Exception) */
88 protected $connFailureErrors = [];
89
90 /** @var bool Whether zlib methods are available to PHP */
91 private $hasZlib;
92
93 /** A number of seconds well above any expected clock skew */
94 private const SAFE_CLOCK_BOUND_SEC = 15;
95 /** A number of seconds well above any expected clock skew and replication lag */
96 private const SAFE_PURGE_DELAY_SEC = 3600;
97 /** Distinct string for tombstones stored in the "serialized" value column */
98 private const TOMB_SERIAL = '';
99 /** Relative seconds-to-live to use for tombstones */
100 private const TOMB_EXPTIME = -self::SAFE_CLOCK_BOUND_SEC;
101 /** How many seconds must pass before triggering a garbage collection */
102 private const GC_DELAY_SEC = 1;
103
104 private const BLOB_VALUE = 0;
105 private const BLOB_EXPIRY = 1;
106 private const BLOB_CASTOKEN = 2;
107
108 /**
109 * Placeholder timestamp to use for TTL_INDEFINITE that can be stored in all RDBMs types.
110 * We use BINARY(14) for MySQL, BLOB for Sqlite, and TIMESTAMPZ for Postgres (which goes
111 * up to 294276 AD). The last second of the year 9999 can be stored in all these cases.
112 * https://www.postgresql.org/docs/9.0/datatype-datetime.html
113 */
114 private const INF_TIMESTAMP_PLACEHOLDER = '99991231235959';
115
116 /**
117 * Create a new backend instance from parameters injected by ObjectCache::newFromParams()
118 *
119 * The database servers must be provided by *either* the "server" parameter, the "servers"
120 * parameter or the "loadBalancer" parameter.
121 *
122 * The parameters are as described at {@link \MediaWiki\MainConfigSchema::ObjectCaches}
123 * except that:
124 *
125 * - the configured "cluster" and main LB fallback modes are implemented by
126 * the wiring by passing "loadBalancerCallback".
127 * - "dbDomain" is required if "loadBalancerCallback" is set, whereas in
128 * config it may be absent.
129 *
130 * @internal
131 *
132 * @param array $params
133 * - server: string
134 * - servers: string[]
135 * - loadBalancerCallback: A closure which provides a LoadBalancer object
136 * - dbDomain: string|false
137 * - multiPrimaryMode: bool
138 * - purgePeriod: int|float
139 * - purgeLimit: int
140 * - tableName: string
141 * - shards: int
142 * - writeBatchSize: int
143 */
144 public function __construct( $params ) {
145 parent::__construct( $params );
146
147 if ( isset( $params['servers'] ) || isset( $params['server'] ) ) {
148 // Configuration uses a direct list of servers.
149 // Object data is horizontally partitioned via key hash.
150 $index = 0;
151 foreach ( ( $params['servers'] ?? [ $params['server'] ] ) as $tag => $info ) {
152 $this->serverInfos[$index] = $info;
153 // Allow integer-indexes arrays for b/c
154 $this->serverTags[$index] = is_string( $tag ) ? $tag : "#$index";
155 ++$index;
156 }
157 } elseif ( isset( $params['loadBalancerCallback'] ) ) {
158 $this->loadBalancerCallback = $params['loadBalancerCallback'];
159 if ( !isset( $params['dbDomain'] ) ) {
160 throw new InvalidArgumentException(
161 __METHOD__ . ": 'dbDomain' is required if 'loadBalancerCallback' is given"
162 );
163 }
164 $this->dbDomain = $params['dbDomain'];
165 $this->useLB = true;
166 } else {
167 throw new InvalidArgumentException(
168 __METHOD__ . " requires 'server', 'servers', or 'loadBalancerCallback'"
169 );
170 }
171
172 $this->purgePeriod = intval( $params['purgePeriod'] ?? $this->purgePeriod );
173 $this->purgeLimit = intval( $params['purgeLimit'] ?? $this->purgeLimit );
174 $this->tableName = $params['tableName'] ?? $this->tableName;
175 $this->numTableShards = intval( $params['shards'] ?? $this->numTableShards );
176 $this->writeBatchSize = intval( $params['writeBatchSize'] ?? $this->writeBatchSize );
177 $this->multiPrimaryMode = $params['multiPrimaryMode'] ?? false;
178
179 $this->attrMap[self::ATTR_DURABILITY] = self::QOS_DURABILITY_RDBMS;
180
181 $this->hasZlib = extension_loaded( 'zlib' );
182 }
183
184 protected function doGet( $key, $flags = 0, &$casToken = null ) {
185 $getToken = ( $casToken === self::PASS_BY_REF );
186 $casToken = null;
187
188 $data = $this->fetchBlobs( [ $key ], $getToken )[$key];
189 if ( $data ) {
190 $result = $this->unserialize( $data[self::BLOB_VALUE] );
191 if ( $getToken && $result !== false ) {
192 $casToken = $data[self::BLOB_CASTOKEN];
193 }
194 $valueSize = strlen( $data[self::BLOB_VALUE] );
195 } else {
196 $result = false;
197 $valueSize = false;
198 }
199
200 $this->updateOpStats( self::METRIC_OP_GET, [ $key => [ 0, $valueSize ] ] );
201
202 return $result;
203 }
204
205 protected function doSet( $key, $value, $exptime = 0, $flags = 0 ) {
206 $mtime = $this->getCurrentTime();
207
208 return $this->modifyBlobs(
209 [ $this, 'modifyTableSpecificBlobsForSet' ],
210 $mtime,
211 [ $key => [ $value, $exptime ] ]
212 );
213 }
214
215 protected function doDelete( $key, $flags = 0 ) {
216 $mtime = $this->getCurrentTime();
217
218 return $this->modifyBlobs(
219 [ $this, 'modifyTableSpecificBlobsForDelete' ],
220 $mtime,
221 [ $key => [] ]
222 );
223 }
224
225 protected function doAdd( $key, $value, $exptime = 0, $flags = 0 ) {
226 $mtime = $this->newLockingWriteSectionModificationTimestamp( $key, $scope );
227 if ( $mtime === null ) {
228 // Timeout or I/O error during lock acquisition
229 return false;
230 }
231
232 return $this->modifyBlobs(
233 [ $this, 'modifyTableSpecificBlobsForAdd' ],
234 $mtime,
235 [ $key => [ $value, $exptime ] ]
236 );
237 }
238
239 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
240 $mtime = $this->newLockingWriteSectionModificationTimestamp( $key, $scope );
241 if ( $mtime === null ) {
242 // Timeout or I/O error during lock acquisition
243 return false;
244 }
245
246 return $this->modifyBlobs(
247 [ $this, 'modifyTableSpecificBlobsForCas' ],
248 $mtime,
249 [ $key => [ $value, $exptime, $casToken ] ]
250 );
251 }
252
253 protected function doChangeTTL( $key, $exptime, $flags ) {
254 $mtime = $this->getCurrentTime();
255
256 return $this->modifyBlobs(
257 [ $this, 'modifyTableSpecificBlobsForChangeTTL' ],
258 $mtime,
259 [ $key => [ $exptime ] ]
260 );
261 }
262
263 protected function doIncrWithInit( $key, $exptime, $step, $init, $flags ) {
264 $mtime = $this->getCurrentTime();
265
266 if ( $flags & self::WRITE_BACKGROUND ) {
267 $callback = [ $this, 'modifyTableSpecificBlobsForIncrInitAsync' ];
268 } else {
269 $callback = [ $this, 'modifyTableSpecificBlobsForIncrInit' ];
270 }
271
272 $result = $this->modifyBlobs(
273 $callback,
274 $mtime,
275 [ $key => [ $step, $init, $exptime ] ],
276 $resByKey
277 ) ? $resByKey[$key] : false;
278
279 return $result;
280 }
281
282 protected function doGetMulti( array $keys, $flags = 0 ) {
283 $result = [];
284 $valueSizeByKey = [];
285
286 $dataByKey = $this->fetchBlobs( $keys );
287 foreach ( $keys as $key ) {
288 $data = $dataByKey[$key];
289 if ( $data ) {
290 $serialValue = $data[self::BLOB_VALUE];
291 $value = $this->unserialize( $serialValue );
292 if ( $value !== false ) {
293 $result[$key] = $value;
294 }
295 $valueSize = strlen( $serialValue );
296 } else {
297 $valueSize = false;
298 }
299 $valueSizeByKey[$key] = [ 0, $valueSize ];
300 }
301
302 $this->updateOpStats( self::METRIC_OP_GET, $valueSizeByKey );
303
304 return $result;
305 }
306
307 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
308 $mtime = $this->getCurrentTime();
309
310 return $this->modifyBlobs(
311 [ $this, 'modifyTableSpecificBlobsForSet' ],
312 $mtime,
313 array_map(
314 static function ( $value ) use ( $exptime ) {
315 return [ $value, $exptime ];
316 },
317 $data
318 )
319 );
320 }
321
322 protected function doDeleteMulti( array $keys, $flags = 0 ) {
323 $mtime = $this->getCurrentTime();
324
325 return $this->modifyBlobs(
326 [ $this, 'modifyTableSpecificBlobsForDelete' ],
327 $mtime,
328 array_fill_keys( $keys, [] )
329 );
330 }
331
332 public function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
333 $mtime = $this->getCurrentTime();
334
335 return $this->modifyBlobs(
336 [ $this, 'modifyTableSpecificBlobsForChangeTTL' ],
337 $mtime,
338 array_fill_keys( $keys, [ $exptime ] )
339 );
340 }
341
342 /**
343 * Get a connection to the specified database
344 *
345 * @param int $shardIndex Server index
346 * @return IMaintainableDatabase
347 * @throws DBConnectionError
348 * @throws UnexpectedValueException
349 */
350 private function getConnection( $shardIndex ) {
351 if ( $this->useLB ) {
352 return $this->getConnectionViaLoadBalancer();
353 }
354
355 // Don't keep timing out trying to connect if the server is down
356 if (
357 isset( $this->connFailureErrors[$shardIndex] ) &&
358 ( $this->getCurrentTime() - $this->connFailureTimes[$shardIndex] ) < 60
359 ) {
360 throw $this->connFailureErrors[$shardIndex];
361 }
362
363 if ( isset( $this->serverInfos[$shardIndex] ) ) {
364 $server = $this->serverInfos[$shardIndex];
365 $conn = $this->getConnectionFromServerInfo( $shardIndex, $server );
366 } else {
367 throw new UnexpectedValueException( "Invalid server index #$shardIndex" );
368 }
369
370 return $conn;
371 }
372
373 /**
374 * Get the server index and table name for a given key
375 * @param string $key
376 * @return array (server index, table name)
377 */
378 private function getKeyLocation( $key ) {
379 // Pick the same shard for sister keys
380 // Using the same hash stop as mc-router for consistency
381 if ( str_contains( $key, '|#|' ) ) {
382 $key = explode( '|#|', $key )[0];
383 }
384 if ( $this->useLB ) {
385 // LoadBalancer based configuration
386 $shardIndex = 0;
387 } else {
388 // Striped array of database servers
389 if ( count( $this->serverTags ) == 1 ) {
390 $shardIndex = 0; // short-circuit
391 } else {
392 $sortedServers = $this->serverTags;
393 ArrayUtils::consistentHashSort( $sortedServers, $key );
394 $shardIndex = array_key_first( $sortedServers );
395 }
396 }
397
398 if ( $this->numTableShards > 1 ) {
399 $hash = hexdec( substr( md5( $key ), 0, 8 ) ) & 0x7fffffff;
400 $tableIndex = $hash % $this->numTableShards;
401 } else {
402 $tableIndex = null;
403 }
404
405 return [ $shardIndex, $this->getTableNameByShard( $tableIndex ) ];
406 }
407
408 /**
409 * Get the table name for a given shard index
410 * @param int|null $index
411 * @return string
412 */
413 private function getTableNameByShard( $index ) {
414 if ( $index !== null && $this->numTableShards > 1 ) {
415 $decimals = strlen( (string)( $this->numTableShards - 1 ) );
416
417 return $this->tableName . sprintf( "%0{$decimals}d", $index );
418 }
419
420 return $this->tableName;
421 }
422
423 /**
424 * @param string[] $keys
425 * @param bool $getCasToken Whether to get a CAS token
426 * @return array<string,array|null> Order-preserved map of (key => (value,expiry,token) or null)
427 */
428 private function fetchBlobs( array $keys, bool $getCasToken = false ) {
429 /** @noinspection PhpUnusedLocalVariableInspection */
430 $silenceScope = $this->silenceTransactionProfiler();
431
432 // Initialize order-preserved per-key results; set values for live keys below
433 $dataByKey = array_fill_keys( $keys, null );
434
435 $readTime = (int)$this->getCurrentTime();
436 $keysByTableByShard = [];
437 foreach ( $keys as $key ) {
438 [ $shardIndex, $partitionTable ] = $this->getKeyLocation( $key );
439 $keysByTableByShard[$shardIndex][$partitionTable][] = $key;
440 }
441
442 foreach ( $keysByTableByShard as $shardIndex => $serverKeys ) {
443 try {
444 $db = $this->getConnection( $shardIndex );
445 foreach ( $serverKeys as $partitionTable => $tableKeys ) {
446 $res = $db->newSelectQueryBuilder()
447 ->select(
448 $getCasToken
449 ? $this->addCasTokenFields( $db, [ 'keyname', 'value', 'exptime' ] )
450 : [ 'keyname', 'value', 'exptime' ] )
451 ->from( $partitionTable )
452 ->where( $this->buildExistenceConditions( $db, $tableKeys, $readTime ) )
453 ->caller( __METHOD__ )
454 ->fetchResultSet();
455 foreach ( $res as $row ) {
456 $row->shardIndex = $shardIndex;
457 $row->tableName = $partitionTable;
458 $dataByKey[$row->keyname] = $row;
459 }
460 }
461 } catch ( DBError $e ) {
462 $this->handleDBError( $e, $shardIndex );
463 }
464 }
465
466 foreach ( $keys as $key ) {
467 $row = $dataByKey[$key] ?? null;
468 if ( !$row ) {
469 continue;
470 }
471
472 $this->debug( __METHOD__ . ": retrieved $key; expiry time is {$row->exptime}" );
473 try {
474 $db = $this->getConnection( $row->shardIndex );
475 $dataByKey[$key] = [
476 self::BLOB_VALUE => $this->dbDecodeSerialValue( $db, $row->value ),
477 self::BLOB_EXPIRY => $this->decodeDbExpiry( $db, $row->exptime ),
478 self::BLOB_CASTOKEN => $getCasToken
479 ? $this->getCasTokenFromRow( $db, $row )
480 : null
481 ];
482 } catch ( DBQueryError $e ) {
483 $this->handleDBError( $e, $row->shardIndex );
484 }
485 }
486
487 return $dataByKey;
488 }
489
490 /**
491 * @param callable $tableWriteCallback Callback the takes the following arguments:
492 * - IDatabase instance
493 * - Partition table name string
494 * - UNIX modification timestamp
495 * - Map of (key => list of arguments) for keys belonging to the server/table partition
496 * - Map of (key => result) [returned]
497 * @param float $mtime UNIX modification timestamp
498 * @param array<string,array> $argsByKey Map of (key => list of arguments)
499 * @param array<string,mixed> &$resByKey Order-preserved map of (key => result) [returned]
500 * @return bool Whether all keys were processed
501 * @param-taint $argsByKey none
502 */
503 private function modifyBlobs(
504 callable $tableWriteCallback,
505 float $mtime,
506 array $argsByKey,
507 &$resByKey = []
508 ) {
509 // Initialize order-preserved per-key results; callbacks mark successful results
510 $resByKey = array_fill_keys( array_keys( $argsByKey ), false );
511
512 /** @noinspection PhpUnusedLocalVariableInspection */
513 $silenceScope = $this->silenceTransactionProfiler();
514
515 $argsByKeyByTableByShard = [];
516 foreach ( $argsByKey as $key => $args ) {
517 [ $shardIndex, $partitionTable ] = $this->getKeyLocation( $key );
518 $argsByKeyByTableByShard[$shardIndex][$partitionTable][$key] = $args;
519 }
520
521 $shardIndexesAffected = [];
522 foreach ( $argsByKeyByTableByShard as $shardIndex => $argsByKeyByTables ) {
523 foreach ( $argsByKeyByTables as $table => $ptKeyArgs ) {
524 try {
525 $db = $this->getConnection( $shardIndex );
526 $shardIndexesAffected[] = $shardIndex;
527 $tableWriteCallback( $db, $table, $mtime, $ptKeyArgs, $resByKey );
528 } catch ( DBError $e ) {
529 $this->handleDBError( $e, $shardIndex );
530 continue;
531 }
532 }
533 }
534
535 $success = !in_array( false, $resByKey, true );
536
537 foreach ( $shardIndexesAffected as $shardIndex ) {
538 try {
539 if (
540 // Random purging is enabled
541 $this->purgePeriod >= 1 &&
542 // Only purge on one in every $this->purgePeriod writes
543 mt_rand( 1, $this->purgePeriod ) == 1 &&
544 // Avoid repeating the delete within a few seconds
545 ( $this->getCurrentTime() - $this->lastGarbageCollect ) > self::GC_DELAY_SEC
546 ) {
547 $this->garbageCollect( $shardIndex );
548 }
549 } catch ( DBError $e ) {
550 $this->handleDBError( $e, $shardIndex );
551 }
552 }
553
554 return $success;
555 }
556
557 /**
558 * Set key/value pairs belonging to a partition table on the given server
559 *
560 * In multi-primary mode, if the current row for a key exists and has a modification token
561 * with a greater integral UNIX timestamp than that of the provided modification timestamp,
562 * then the write to that key will be aborted with a "false" result. Successfully modified
563 * key rows will be assigned a new modification token using the provided timestamp.
564 *
565 * @param IDatabase $db Handle to the database server where the argument keys belong
566 * @param string $ptable Name of the partition table where the argument keys belong
567 * @param float $mtime UNIX modification timestamp
568 * @param array<string,array> $argsByKey Non-empty (key => (value,exptime)) map
569 * @param array<string,mixed> &$resByKey Map of (key => result) for successful writes [returned]
570 * @throws DBError
571 */
572 private function modifyTableSpecificBlobsForSet(
573 IDatabase $db,
574 string $ptable,
575 float $mtime,
576 array $argsByKey,
577 array &$resByKey
578 ) {
579 $valueSizesByKey = [];
580
581 $mt = $this->makeTimestampedModificationToken( $mtime, $db );
582
583 $rows = [];
584 foreach ( $argsByKey as $key => [ $value, $exptime ] ) {
585 $expiry = $this->makeNewKeyExpiry( $exptime, (int)$mtime );
586 $serialValue = $this->getSerialized( $value, $key );
587 $rows[] = $this->buildUpsertRow( $db, $key, $serialValue, $expiry, $mt );
588
589 $valueSizesByKey[$key] = [ strlen( $serialValue ), 0 ];
590 }
591
592 if ( $this->multiPrimaryMode ) {
593 $db->newInsertQueryBuilder()
594 ->insertInto( $ptable )
595 ->rows( $rows )
596 ->onDuplicateKeyUpdate()
597 ->uniqueIndexFields( [ 'keyname' ] )
598 ->set( $this->buildMultiUpsertSetForOverwrite( $db, $mt ) )
599 ->caller( __METHOD__ )->execute();
600 } else {
601 // T288998: use REPLACE, if possible, to avoid cluttering the binlogs
602 $db->newReplaceQueryBuilder()
603 ->replaceInto( $ptable )
604 ->rows( $rows )
605 ->uniqueIndexFields( [ 'keyname' ] )
606 ->caller( __METHOD__ )->execute();
607 }
608
609 foreach ( $argsByKey as $key => $unused ) {
610 $resByKey[$key] = true;
611 }
612
613 $this->updateOpStats( self::METRIC_OP_SET, $valueSizesByKey );
614 }
615
616 /**
617 * Purge/tombstone key/value pairs belonging to a partition table on the given server
618 *
619 * In multi-primary mode, if the current row for a key exists and has a modification token
620 * with a greater integral UNIX timestamp than that of the provided modification timestamp,
621 * then the write to that key will be aborted with a "false" result. Successfully modified
622 * key rows will be assigned a new modification token/timestamp, an empty value, and an
623 * expiration timestamp dated slightly before the new modification timestamp.
624 *
625 * @param IDatabase $db Handle to the database server where the argument keys belong
626 * @param string $ptable Name of the partition table where the argument keys belong
627 * @param float $mtime UNIX modification timestamp
628 * @param array<string,array> $argsByKey Non-empty (key => []) map
629 * @param array<string,mixed> &$resByKey Map of (key => result) prefilled with false [returned]
630 * @throws DBError
631 */
632 private function modifyTableSpecificBlobsForDelete(
633 IDatabase $db,
634 string $ptable,
635 float $mtime,
636 array $argsByKey,
637 array &$resByKey
638 ) {
639 if ( $this->multiPrimaryMode ) {
640 // Tombstone keys in order to respect eventual consistency
641 $mt = $this->makeTimestampedModificationToken( $mtime, $db );
642 $expiry = $this->makeNewKeyExpiry( self::TOMB_EXPTIME, (int)$mtime );
643 $queryBuilder = $db->newInsertQueryBuilder()
644 ->insertInto( $ptable )
645 ->onDuplicateKeyUpdate()
646 ->uniqueIndexFields( [ 'keyname' ] )
647 ->set( $this->buildMultiUpsertSetForOverwrite( $db, $mt ) );
648 foreach ( $argsByKey as $key => $arg ) {
649 $queryBuilder->row( $this->buildUpsertRow( $db, $key, self::TOMB_SERIAL, $expiry, $mt ) );
650 }
651 $queryBuilder->caller( __METHOD__ )->execute();
652 } else {
653 // Just purge the keys since there is only one primary (e.g. "source of truth")
654 $db->newDeleteQueryBuilder()
655 ->deleteFrom( $ptable )
656 ->where( [ 'keyname' => array_keys( $argsByKey ) ] )
657 ->caller( __METHOD__ )->execute();
658 }
659
660 foreach ( $argsByKey as $key => $arg ) {
661 $resByKey[$key] = true;
662 }
663
664 $this->updateOpStats( self::METRIC_OP_DELETE, array_keys( $argsByKey ) );
665 }
666
667 /**
668 * Insert key/value pairs belonging to a partition table on the given server
669 *
670 * If the current row for a key exists and has an integral UNIX timestamp of expiration
671 * greater than that of the provided modification timestamp, then the write to that key
672 * will be aborted with a "false" result. Acquisition of advisory key locks must be handled
673 * by calling functions.
674 *
675 * In multi-primary mode, if the current row for a key exists and has a modification token
676 * with a greater integral UNIX timestamp than that of the provided modification timestamp,
677 * then the write to that key will be aborted with a "false" result. Successfully modified
678 * key rows will be assigned a new modification token/timestamp.
679 *
680 * @param IDatabase $db Handle to the database server where the argument keys belong
681 * @param string $ptable Name of the partition table where the argument keys belong
682 * @param float $mtime UNIX modification timestamp
683 * @param array<string,array> $argsByKey Non-empty (key => (value,exptime)) map
684 * @param array<string,mixed> &$resByKey Map of (key => result) prefilled with false [returned]
685 * @throws DBError
686 */
687 private function modifyTableSpecificBlobsForAdd(
688 IDatabase $db,
689 string $ptable,
690 float $mtime,
691 array $argsByKey,
692 array &$resByKey
693 ) {
694 $valueSizesByKey = [];
695
696 $mt = $this->makeTimestampedModificationToken( $mtime, $db );
697
698 // This check must happen outside the write query to respect eventual consistency
699 $existingKeys = $db->newSelectQueryBuilder()
700 ->select( 'keyname' )
701 ->from( $ptable )
702 ->where( $this->buildExistenceConditions( $db, array_keys( $argsByKey ), (int)$mtime ) )
703 ->caller( __METHOD__ )
704 ->fetchFieldValues();
705 $existingByKey = array_fill_keys( $existingKeys, true );
706
707 $rows = [];
708 foreach ( $argsByKey as $key => [ $value, $exptime ] ) {
709 if ( isset( $existingByKey[$key] ) ) {
710 $this->logger->debug( __METHOD__ . ": $key already exists" );
711 continue;
712 }
713
714 $serialValue = $this->getSerialized( $value, $key );
715 $expiry = $this->makeNewKeyExpiry( $exptime, (int)$mtime );
716 $valueSizesByKey[$key] = [ strlen( $serialValue ), 0 ];
717 $rows[] = $this->buildUpsertRow( $db, $key, $serialValue, $expiry, $mt );
718 }
719 if ( !$rows ) {
720 return;
721 }
722 $db->newInsertQueryBuilder()
723 ->insertInto( $ptable )
724 ->rows( $rows )
725 ->onDuplicateKeyUpdate()
726 ->uniqueIndexFields( [ 'keyname' ] )
727 ->set( $this->buildMultiUpsertSetForOverwrite( $db, $mt ) )
728 ->caller( __METHOD__ )->execute();
729
730 foreach ( $argsByKey as $key => $unused ) {
731 $resByKey[$key] = !isset( $existingByKey[$key] );
732 }
733
734 $this->updateOpStats( self::METRIC_OP_ADD, $valueSizesByKey );
735 }
736
737 /**
738 * Insert key/value pairs belonging to a partition table on the given server
739 *
740 * If the current row for a key exists, has an integral UNIX timestamp of expiration greater
741 * than that of the provided modification timestamp, and the CAS token does not match, then
742 * the write to that key will be aborted with a "false" result. Acquisition of advisory key
743 * locks must be handled by calling functions.
744 *
745 * In multi-primary mode, if the current row for a key exists and has a modification token
746 * with a greater integral UNIX timestamp than that of the provided modification timestamp,
747 * then the write to that key will be aborted with a "false" result. Successfully modified
748 * key rows will be assigned a new modification token/timestamp.
749 *
750 * @param IDatabase $db Handle to the database server where the argument keys belong
751 * @param string $ptable Name of the partition table where the argument keys belong
752 * @param float $mtime UNIX modification timestamp
753 * @param array<string,array> $argsByKey Non-empty (key => (value, exptime, CAS token)) map
754 * @param array<string,mixed> &$resByKey Map of (key => result) prefilled with false [returned]
755 * @throws DBError
756 */
757 private function modifyTableSpecificBlobsForCas(
758 IDatabase $db,
759 string $ptable,
760 float $mtime,
761 array $argsByKey,
762 array &$resByKey
763 ) {
764 $valueSizesByKey = [];
765
766 $mt = $this->makeTimestampedModificationToken( $mtime, $db );
767
768 // This check must happen outside the write query to respect eventual consistency
769 $res = $db->newSelectQueryBuilder()
770 ->select( $this->addCasTokenFields( $db, [ 'keyname' ] ) )
771 ->from( $ptable )
772 ->where( $this->buildExistenceConditions( $db, array_keys( $argsByKey ), (int)$mtime ) )
773 ->caller( __METHOD__ )
774 ->fetchResultSet();
775
776 $curTokensByKey = [];
777 foreach ( $res as $row ) {
778 $curTokensByKey[$row->keyname] = $this->getCasTokenFromRow( $db, $row );
779 }
780
781 $nonMatchingByKey = [];
782 $rows = [];
783 foreach ( $argsByKey as $key => [ $value, $exptime, $casToken ] ) {
784 $curToken = $curTokensByKey[$key] ?? null;
785 if ( $curToken === null ) {
786 $nonMatchingByKey[$key] = true;
787 $this->logger->debug( __METHOD__ . ": $key does not exists" );
788 continue;
789 }
790
791 if ( $curToken !== $casToken ) {
792 $nonMatchingByKey[$key] = true;
793 $this->logger->debug( __METHOD__ . ": $key does not have a matching token" );
794 continue;
795 }
796
797 $serialValue = $this->getSerialized( $value, $key );
798 $expiry = $this->makeNewKeyExpiry( $exptime, (int)$mtime );
799 $valueSizesByKey[$key] = [ strlen( $serialValue ), 0 ];
800
801 $rows[] = $this->buildUpsertRow( $db, $key, $serialValue, $expiry, $mt );
802 }
803 if ( !$rows ) {
804 return;
805 }
806 $db->newInsertQueryBuilder()
807 ->insertInto( $ptable )
808 ->rows( $rows )
809 ->onDuplicateKeyUpdate()
810 ->uniqueIndexFields( [ 'keyname' ] )
811 ->set( $this->buildMultiUpsertSetForOverwrite( $db, $mt ) )
812 ->caller( __METHOD__ )->execute();
813
814 foreach ( $argsByKey as $key => $unused ) {
815 $resByKey[$key] = !isset( $nonMatchingByKey[$key] );
816 }
817
818 $this->updateOpStats( self::METRIC_OP_CAS, $valueSizesByKey );
819 }
820
821 /**
822 * Update the TTL for keys belonging to a partition table on the given server
823 *
824 * If no current row for a key exists or the current row has an integral UNIX timestamp of
825 * expiration less than that of the provided modification timestamp, then the write to that
826 * key will be aborted with a "false" result.
827 *
828 * In multi-primary mode, if the current row for a key exists and has a modification token
829 * with a greater integral UNIX timestamp than that of the provided modification timestamp,
830 * then the write to that key will be aborted with a "false" result. Successfully modified
831 * key rows will be assigned a new modification token/timestamp.
832 *
833 * @param IDatabase $db Handle to the database server where the argument keys belong
834 * @param string $ptable Name of the partition table where the argument keys belong
835 * @param float $mtime UNIX modification timestamp
836 * @param array<string,array> $argsByKey Non-empty (key => (exptime)) map
837 * @param array<string,mixed> &$resByKey Map of (key => result) prefilled with false [returned]
838 * @throws DBError
839 */
840 private function modifyTableSpecificBlobsForChangeTTL(
841 IDatabase $db,
842 string $ptable,
843 float $mtime,
844 array $argsByKey,
845 array &$resByKey
846 ) {
847 if ( $this->multiPrimaryMode ) {
848 $mt = $this->makeTimestampedModificationToken( $mtime, $db );
849
850 $res = $db->newSelectQueryBuilder()
851 ->select( [ 'keyname', 'value' ] )
852 ->from( $ptable )
853 ->where( $this->buildExistenceConditions( $db, array_keys( $argsByKey ), (int)$mtime ) )
854 ->caller( __METHOD__ )
855 ->fetchResultSet();
856
857 $rows = [];
858 $existingKeys = [];
859 foreach ( $res as $curRow ) {
860 $key = $curRow->keyname;
861 $existingKeys[$key] = true;
862 $serialValue = $this->dbDecodeSerialValue( $db, $curRow->value );
863 [ $exptime ] = $argsByKey[$key];
864 $expiry = $this->makeNewKeyExpiry( $exptime, (int)$mtime );
865 $rows[] = $this->buildUpsertRow( $db, $key, $serialValue, $expiry, $mt );
866 }
867 if ( !$rows ) {
868 return;
869 }
870 $db->newInsertQueryBuilder()
871 ->insertInto( $ptable )
872 ->rows( $rows )
873 ->onDuplicateKeyUpdate()
874 ->uniqueIndexFields( [ 'keyname' ] )
875 ->set( $this->buildMultiUpsertSetForOverwrite( $db, $mt ) )
876 ->caller( __METHOD__ )->execute();
877
878 foreach ( $argsByKey as $key => $unused ) {
879 $resByKey[$key] = isset( $existingKeys[$key] );
880 }
881 } else {
882 $keysBatchesByExpiry = [];
883 foreach ( $argsByKey as $key => [ $exptime ] ) {
884 $expiry = $this->makeNewKeyExpiry( $exptime, (int)$mtime );
885 $keysBatchesByExpiry[$expiry][] = $key;
886 }
887
888 $existingCount = 0;
889 foreach ( $keysBatchesByExpiry as $expiry => $keyBatch ) {
890 $db->newUpdateQueryBuilder()
891 ->update( $ptable )
892 ->set( [ 'exptime' => $this->encodeDbExpiry( $db, $expiry ) ] )
893 ->where( $this->buildExistenceConditions( $db, $keyBatch, (int)$mtime ) )
894 ->caller( __METHOD__ )->execute();
895 $existingCount += $db->affectedRows();
896 }
897 if ( $existingCount === count( $argsByKey ) ) {
898 foreach ( $argsByKey as $key => $args ) {
899 $resByKey[$key] = true;
900 }
901 }
902 }
903
904 $this->updateOpStats( self::METRIC_OP_CHANGE_TTL, array_keys( $argsByKey ) );
905 }
906
907 /**
908 * Either increment a counter key, if it exists, or initialize it, otherwise
909 *
910 * If no current row for a key exists or the current row has an integral UNIX timestamp of
911 * expiration less than that of the provided modification timestamp, then the key row will
912 * be set to the initial value. Otherwise, the current row will be incremented.
913 *
914 * In multi-primary mode, if the current row for a key exists and has a modification token
915 * with a greater integral UNIX timestamp than that of the provided modification timestamp,
916 * then the write to that key will be aborted with a "false" result. Successfully initialized
917 * key rows will be assigned a new modification token/timestamp.
918 *
919 * @param IDatabase $db Handle to the database server where the argument keys belong
920 * @param string $ptable Name of the partition table where the argument keys belong
921 * @param float $mtime UNIX modification timestamp
922 * @param array<string,array> $argsByKey Non-empty (key => (step, init, exptime) map
923 * @param array<string,mixed> &$resByKey Map of (key => result) prefilled with false [returned]
924 * @throws DBError
925 */
926 private function modifyTableSpecificBlobsForIncrInit(
927 IDatabase $db,
928 string $ptable,
929 float $mtime,
930 array $argsByKey,
931 array &$resByKey
932 ) {
933 foreach ( $argsByKey as $key => [ $step, $init, $exptime ] ) {
934 $mt = $this->makeTimestampedModificationToken( $mtime, $db );
935 $expiry = $this->makeNewKeyExpiry( $exptime, (int)$mtime );
936
937 // Use a transaction so that changes from other threads are not visible due to
938 // "consistent reads". This way, the exact post-increment value can be returned.
939 // The "live key exists" check can go inside the write query and remain safe for
940 // replication since the TTL for such keys is either indefinite or very short.
941 $atomic = $db->startAtomic( __METHOD__, IDatabase::ATOMIC_CANCELABLE );
942 try {
943 $db->newInsertQueryBuilder()
944 ->insertInto( $ptable )
945 ->rows( $this->buildUpsertRow( $db, $key, $init, $expiry, $mt ) )
946 ->onDuplicateKeyUpdate()
947 ->uniqueIndexFields( [ 'keyname' ] )
948 ->set( $this->buildIncrUpsertSet( $db, $step, $init, $expiry, $mt, (int)$mtime ) )
949 ->caller( __METHOD__ )->execute();
950 $affectedCount = $db->affectedRows();
951 $row = $db->newSelectQueryBuilder()
952 ->select( 'value' )
953 ->from( $ptable )
954 ->where( [ 'keyname' => $key ] )
955 ->caller( __METHOD__ )
956 ->fetchRow();
957 } catch ( Exception $e ) {
958 $db->cancelAtomic( __METHOD__, $atomic );
959 throw $e;
960 }
961 $db->endAtomic( __METHOD__ );
962
963 if ( !$affectedCount || $row === false ) {
964 $this->logger->warning( __METHOD__ . ": failed to set new $key value" );
965 continue;
966 }
967
968 $serialValue = $this->dbDecodeSerialValue( $db, $row->value );
969 if ( !$this->isInteger( $serialValue ) ) {
970 $this->logger->warning( __METHOD__ . ": got non-integer $key value" );
971 continue;
972 }
973
974 $resByKey[$key] = (int)$serialValue;
975 }
976
977 $this->updateOpStats( self::METRIC_OP_INCR, array_keys( $argsByKey ) );
978 }
979
980 /**
981 * Same as modifyTableSpecificBlobsForIncrInit() but does not return the
982 * new value.
983 *
984 * @param IDatabase $db
985 * @param string $ptable
986 * @param float $mtime
987 * @param array<string,array> $argsByKey
988 * @param array<string,mixed> &$resByKey
989 * @throws DBError
990 */
991 private function modifyTableSpecificBlobsForIncrInitAsync(
992 IDatabase $db,
993 string $ptable,
994 float $mtime,
995 array $argsByKey,
996 array &$resByKey
997 ) {
998 foreach ( $argsByKey as $key => [ $step, $init, $exptime ] ) {
999 $mt = $this->makeTimestampedModificationToken( $mtime, $db );
1000 $expiry = $this->makeNewKeyExpiry( $exptime, (int)$mtime );
1001 $db->newInsertQueryBuilder()
1002 ->insertInto( $ptable )
1003 ->rows( $this->buildUpsertRow( $db, $key, $init, $expiry, $mt ) )
1004 ->onDuplicateKeyUpdate()
1005 ->uniqueIndexFields( [ 'keyname' ] )
1006 ->set( $this->buildIncrUpsertSet( $db, $step, $init, $expiry, $mt, (int)$mtime ) )
1007 ->caller( __METHOD__ )->execute();
1008 if ( !$db->affectedRows() ) {
1009 $this->logger->warning( __METHOD__ . ": failed to set new $key value" );
1010 } else {
1011 $resByKey[$key] = true;
1012 }
1013 }
1014 }
1015
1016 /**
1017 * @param int $exptime Relative or absolute expiration
1018 * @param int $nowTsUnix Current UNIX timestamp
1019 * @return int UNIX timestamp or TTL_INDEFINITE
1020 */
1021 private function makeNewKeyExpiry( $exptime, int $nowTsUnix ) {
1022 $expiry = $this->getExpirationAsTimestamp( $exptime );
1023 // Eventual consistency requires the preservation of recently modified keys.
1024 // Do not create rows with `exptime` fields so low that they might get garbage
1025 // collected before being replicated.
1026 if ( $expiry !== self::TTL_INDEFINITE ) {
1027 $expiry = max( $expiry, $nowTsUnix - self::SAFE_CLOCK_BOUND_SEC );
1028 }
1029
1030 return $expiry;
1031 }
1032
1033 /**
1034 * Get a scoped lock and modification timestamp for a critical section of reads/writes
1035 *
1036 * This is used instead of BagOStuff::getCurrentTime() for certain writes (such as "add",
1037 * "incr", and "cas"), for which we want to support tight race conditions where the same
1038 * key is repeatedly written to by multiple web servers that each get to see the previous
1039 * value, act on it, and modify it in some way.
1040 *
1041 * It is assumed that this method is normally only invoked from the primary datacenter.
1042 * A lock is acquired on the primary server of the local datacenter in order to avoid race
1043 * conditions within the critical section. The clock on the SQL server is used to get the
1044 * modification timestamp in order to minimize issues with clock drift between web servers;
1045 * thus key writes will not be rejected due to some web servers having lagged clocks.
1046 *
1047 * @param string $key
1048 * @param ?ScopedCallback &$scope Unlocker callback; null on failure [returned]
1049 * @return float|null UNIX timestamp with 6 decimal places; null on failure
1050 */
1051 private function newLockingWriteSectionModificationTimestamp( $key, &$scope ) {
1052 if ( !$this->lock( $key, 0 ) ) {
1053 return null;
1054 }
1055
1056 $scope = new ScopedCallback( function () use ( $key ) {
1057 $this->unlock( $key );
1058 } );
1059
1060 // sprintf is used to adjust precision
1061 return (float)sprintf( '%.6F', $this->locks[$key][self::LOCK_TIME] );
1062 }
1063
1064 /**
1065 * Make a `modtoken` column value with the original time and source database server of a write
1066 *
1067 * @param float $mtime UNIX modification timestamp
1068 * @param IDatabase $db Handle to the primary database server sourcing the write
1069 * @return string String of the form "<SECONDS_SOURCE><MICROSECONDS>", where SECONDS_SOURCE
1070 * is "<35 bit seconds portion of UNIX time><32 bit database server ID>" as 13 base 36 chars,
1071 * and MICROSECONDS is "<20 bit microseconds portion of UNIX time>" as 4 base 36 chars
1072 */
1073 private function makeTimestampedModificationToken( float $mtime, IDatabase $db ) {
1074 // We have reserved space for upto 6 digits in the microsecond portion of the token.
1075 // This is for future use only (maybe CAS tokens) and not currently used.
1076 // It is currently populated by the microsecond portion returned by microtime,
1077 // which generally has fewer than 6 digits of meaningful precision but can still be useful
1078 // in debugging (to see the token continuously change even during rapid testing).
1079 $seconds = (int)$mtime;
1080 [ , $microseconds ] = explode( '.', sprintf( '%.6F', $mtime ) );
1081
1082 $id = sprintf( '%u', crc32( $db->getServerName() ) );
1083
1084 $token = implode( '', [
1085 // 67 bit integral portion of UNIX timestamp, qualified
1086 \Wikimedia\base_convert(
1087 // 35 bit integral seconds portion of UNIX timestamp
1088 str_pad( base_convert( (string)$seconds, 10, 2 ), 35, '0', STR_PAD_LEFT ) .
1089 // 32 bit ID of the primary database server handling the write
1090 str_pad( base_convert( $id, 10, 2 ), 32, '0', STR_PAD_LEFT ),
1091 2,
1092 36,
1093 13
1094 ),
1095 // 20 bit fractional portion of UNIX timestamp, as integral microseconds
1096 str_pad( base_convert( $microseconds, 10, 36 ), 4, '0', STR_PAD_LEFT )
1097 ] );
1098
1099 if ( strlen( $token ) !== 17 ) {
1100 throw new RuntimeException( "Modification timestamp overflow detected" );
1101 }
1102
1103 return $token;
1104 }
1105
1106 /**
1107 * WHERE conditions that check for existence and liveness of keys
1108 *
1109 * @param IDatabase $db
1110 * @param string[]|string $keys
1111 * @param int $time UNIX modification timestamp
1112 * @return array
1113 */
1114 private function buildExistenceConditions( IDatabase $db, $keys, int $time ) {
1115 // Note that tombstones always have past expiration dates
1116 return [
1117 'keyname' => $keys,
1118 $db->expr( 'exptime', '>=', $db->timestamp( $time ) )
1119 ];
1120 }
1121
1122 /**
1123 * INSERT array for handling key writes/overwrites when no live nor stale key exists
1124 *
1125 * @param IDatabase $db
1126 * @param string $key
1127 * @param string|int $serialValue New value
1128 * @param int $expiry Expiration timestamp or TTL_INDEFINITE
1129 * @param string $mt Modification token
1130 * @return array
1131 */
1132 private function buildUpsertRow(
1133 IDatabase $db,
1134 $key,
1135 $serialValue,
1136 int $expiry,
1137 string $mt
1138 ) {
1139 $row = [
1140 'keyname' => $key,
1141 'value' => $this->dbEncodeSerialValue( $db, $serialValue ),
1142 'exptime' => $this->encodeDbExpiry( $db, $expiry )
1143 ];
1144 if ( $this->multiPrimaryMode ) {
1145 $row['modtoken'] = $mt;
1146 }
1147
1148 return $row;
1149 }
1150
1151 /**
1152 * SET array for handling key overwrites when a live or stale key exists
1153 *
1154 * @param IDatabase $db
1155 * @param string $mt Modification token
1156 * @return array
1157 */
1158 private function buildMultiUpsertSetForOverwrite( IDatabase $db, string $mt ) {
1159 $expressionsByColumn = [
1160 'value' => $db->buildExcludedValue( 'value' ),
1161 'exptime' => $db->buildExcludedValue( 'exptime' )
1162 ];
1163
1164 $set = [];
1165 if ( $this->multiPrimaryMode ) {
1166 // The query might take a while to replicate, during which newer values might get
1167 // written. Qualify the query so that it does not override such values. Note that
1168 // duplicate tokens generated around the same time for a key should still result
1169 // in convergence given the use of server_id in modtoken (providing a total order
1170 // among primary DB servers) and MySQL binlog ordering (providing a total order
1171 // for writes replicating from a given primary DB server).
1172 $expressionsByColumn['modtoken'] = $db->addQuotes( $mt );
1173 foreach ( $expressionsByColumn as $column => $updateExpression ) {
1174 $rhs = $db->conditional(
1175 $db->addQuotes( substr( $mt, 0, 13 ) ) . ' >= ' .
1176 $db->buildSubString( 'modtoken', 1, 13 ),
1177 $updateExpression,
1178 $column
1179 );
1180 $set[$column] = new RawSQLValue( $rhs );
1181 }
1182 } else {
1183 foreach ( $expressionsByColumn as $column => $updateExpression ) {
1184 $set[$column] = new RawSQLValue( $updateExpression );
1185 }
1186 }
1187
1188 return $set;
1189 }
1190
1191 /**
1192 * SET array for handling key overwrites when a live or stale key exists
1193 *
1194 * @param IDatabase $db
1195 * @param int $step Positive counter incrementation value
1196 * @param int $init Positive initial counter value
1197 * @param int $expiry Expiration timestamp or TTL_INDEFINITE
1198 * @param string $mt Modification token
1199 * @param int $mtUnixTs UNIX timestamp of modification token
1200 * @return array
1201 */
1202 private function buildIncrUpsertSet(
1203 IDatabase $db,
1204 int $step,
1205 int $init,
1206 int $expiry,
1207 string $mt,
1208 int $mtUnixTs
1209 ) {
1210 // Map of (column => (SQL for non-expired key rows, SQL for expired key rows))
1211 $expressionsByColumn = [
1212 'value' => [
1213 $db->buildIntegerCast( 'value' ) . " + {$db->addQuotes( $step )}",
1214 $db->addQuotes( $this->dbEncodeSerialValue( $db, $init ) )
1215 ],
1216 'exptime' => [
1217 'exptime',
1218 $db->addQuotes( $this->encodeDbExpiry( $db, $expiry ) )
1219 ]
1220 ];
1221 if ( $this->multiPrimaryMode ) {
1222 $expressionsByColumn['modtoken'] = [ 'modtoken', $db->addQuotes( $mt ) ];
1223 }
1224
1225 $set = [];
1226 foreach ( $expressionsByColumn as $column => [ $updateExpression, $initExpression ] ) {
1227 $rhs = $db->conditional(
1228 $db->expr( 'exptime', '>=', $db->timestamp( $mtUnixTs ) ),
1229 $updateExpression,
1230 $initExpression
1231 );
1232 $set[$column] = new RawSQLValue( $rhs );
1233 }
1234
1235 return $set;
1236 }
1237
1238 /**
1239 * @param IDatabase $db
1240 * @param int $expiry UNIX timestamp of expiration or TTL_INDEFINITE
1241 * @return string
1242 */
1243 private function encodeDbExpiry( IDatabase $db, int $expiry ) {
1244 return ( $expiry === self::TTL_INDEFINITE )
1245 // Use the maximum timestamp that the column can store
1246 ? $db->timestamp( self::INF_TIMESTAMP_PLACEHOLDER )
1247 // Convert the absolute timestamp into the DB timestamp format
1248 : $db->timestamp( $expiry );
1249 }
1250
1251 /**
1252 * @param IDatabase $db
1253 * @param string $dbExpiry DB timestamp of expiration
1254 * @return int UNIX timestamp of expiration or TTL_INDEFINITE
1255 */
1256 private function decodeDbExpiry( IDatabase $db, string $dbExpiry ) {
1257 return ( $dbExpiry === $db->timestamp( self::INF_TIMESTAMP_PLACEHOLDER ) )
1258 ? self::TTL_INDEFINITE
1259 : (int)ConvertibleTimestamp::convert( TS_UNIX, $dbExpiry );
1260 }
1261
1262 /**
1263 * @param IDatabase $db
1264 * @param string|int $serialValue
1265 * @return string
1266 */
1267 private function dbEncodeSerialValue( IDatabase $db, $serialValue ) {
1268 return is_int( $serialValue ) ? (string)$serialValue : $db->encodeBlob( $serialValue );
1269 }
1270
1271 /**
1272 * @param IDatabase $db
1273 * @param Blob|string|int $blob
1274 * @return string|int
1275 */
1276 private function dbDecodeSerialValue( IDatabase $db, $blob ) {
1277 return $this->isInteger( $blob ) ? (int)$blob : $db->decodeBlob( $blob );
1278 }
1279
1280 /**
1281 * Either append a 'castoken' field or append the fields needed to compute the CAS token
1282 *
1283 * @param IDatabase $db
1284 * @param string[] $fields SELECT field array
1285 * @return string[] SELECT field array
1286 */
1287 private function addCasTokenFields( IDatabase $db, array $fields ) {
1288 $type = $db->getType();
1289
1290 if ( $type === 'mysql' ) {
1291 $fields['castoken'] = $db->buildConcat( [
1292 'SHA1(value)',
1293 $db->addQuotes( '@' ),
1294 'exptime'
1295 ] );
1296 } elseif ( $type === 'postgres' ) {
1297 $fields['castoken'] = $db->buildConcat( [
1298 'md5(value)',
1299 $db->addQuotes( '@' ),
1300 'exptime'
1301 ] );
1302 } else {
1303 if ( !in_array( 'value', $fields, true ) ) {
1304 $fields[] = 'value';
1305 }
1306 if ( !in_array( 'exptime', $fields, true ) ) {
1307 $fields[] = 'exptime';
1308 }
1309 }
1310
1311 return $fields;
1312 }
1313
1314 /**
1315 * Get a CAS token from a SELECT result row
1316 *
1317 * @param IDatabase $db
1318 * @param stdClass $row A row for a key
1319 * @return string CAS token
1320 */
1321 private function getCasTokenFromRow( IDatabase $db, stdClass $row ) {
1322 if ( isset( $row->castoken ) ) {
1323 $token = $row->castoken;
1324 } else {
1325 $token = sha1( $this->dbDecodeSerialValue( $db, $row->value ) ) . '@' . $row->exptime;
1326 $this->logger->debug( __METHOD__ . ": application computed hash for CAS token" );
1327 }
1328
1329 return $token;
1330 }
1331
1332 /**
1333 * @param int $shardIndex
1334 * @throws DBError
1335 */
1336 private function garbageCollect( $shardIndex ) {
1337 // set right away, avoid queuing duplicate async callbacks
1338 $this->lastGarbageCollect = $this->getCurrentTime();
1339
1340 $garbageCollector = function () use ( $shardIndex ) {
1341 $db = $this->getConnection( $shardIndex );
1342 /** @noinspection PhpUnusedLocalVariableInspection */
1343 $silenceScope = $this->silenceTransactionProfiler();
1344 $this->deleteServerObjectsExpiringBefore(
1345 $db,
1346 (int)$this->getCurrentTime(),
1347 $this->purgeLimit
1348 );
1349 $this->lastGarbageCollect = $this->getCurrentTime();
1350 };
1351
1352 if ( $this->asyncHandler ) {
1353 ( $this->asyncHandler )( $garbageCollector );
1354 } else {
1355 $garbageCollector();
1356 }
1357 }
1358
1359 /**
1360 * @deprecated since 1.41, use deleteObjectsExpiringBefore() instead
1361 */
1362 public function expireAll() {
1363 wfDeprecated( __METHOD__, '1.41' );
1364 $this->deleteObjectsExpiringBefore( (int)$this->getCurrentTime() );
1365 }
1366
1367 public function deleteObjectsExpiringBefore(
1368 $timestamp,
1369 ?callable $progress = null,
1370 $limit = INF,
1371 ?string $tag = null
1372 ) {
1373 /** @noinspection PhpUnusedLocalVariableInspection */
1374 $silenceScope = $this->silenceTransactionProfiler();
1375
1376 if ( $tag !== null ) {
1377 // Purge one server only, to support concurrent purging in large wiki farms (T282761).
1378 $shardIndexes = [];
1379 if ( !$this->serverTags ) {
1380 throw new InvalidArgumentException( "Given a tag but no tags are configured" );
1381 }
1382 foreach ( $this->serverTags as $serverShardIndex => $serverTag ) {
1383 if ( $tag === $serverTag ) {
1384 $shardIndexes[] = $serverShardIndex;
1385 break;
1386 }
1387 }
1388 if ( !$shardIndexes ) {
1389 throw new InvalidArgumentException( "Unknown server tag: $tag" );
1390 }
1391 } else {
1392 $shardIndexes = $this->getShardServerIndexes();
1393 shuffle( $shardIndexes );
1394 }
1395
1396 $ok = true;
1397 $numServers = count( $shardIndexes );
1398
1399 $keysDeletedCount = 0;
1400 foreach ( $shardIndexes as $numServersDone => $shardIndex ) {
1401 try {
1402 $db = $this->getConnection( $shardIndex );
1403
1404 // Avoid deadlock (T330377)
1405 $lockKey = "SqlBagOStuff-purge-shard:$shardIndex";
1406 if ( !$db->lock( $lockKey, __METHOD__, 0 ) ) {
1407 $this->logger->info( "SqlBagOStuff purge for shard $shardIndex already locked, skip" );
1408 continue;
1409 }
1410
1411 $this->deleteServerObjectsExpiringBefore(
1412 $db,
1413 $timestamp,
1414 $limit,
1415 $keysDeletedCount,
1416 [ 'fn' => $progress, 'serversDone' => $numServersDone, 'serversTotal' => $numServers ]
1417 );
1418 $db->unlock( $lockKey, __METHOD__ );
1419 } catch ( DBError $e ) {
1420 $this->handleDBError( $e, $shardIndex );
1421 $ok = false;
1422 }
1423 }
1424
1425 return $ok;
1426 }
1427
1428 /**
1429 * @param IDatabase $db
1430 * @param string|int $timestamp
1431 * @param int|float $limit Maximum number of rows to delete in total or INF for no limit
1432 * @param int &$keysDeletedCount
1433 * @param array|null $progress
1434 * @phan-param array{fn:?callback,serversDone:int,serversTotal:int}|null $progress
1435 * @throws DBError
1436 */
1437 private function deleteServerObjectsExpiringBefore(
1438 IDatabase $db,
1439 $timestamp,
1440 $limit,
1441 &$keysDeletedCount = 0,
1442 ?array $progress = null
1443 ) {
1444 $cutoffUnix = ConvertibleTimestamp::convert( TS_UNIX, $timestamp );
1445 if ( $this->multiPrimaryMode ) {
1446 // Eventual consistency requires the preservation of any key that was recently
1447 // modified. The key must exist on this database server long enough for the server
1448 // to receive, via replication, all writes to the key with lower timestamps. Such
1449 // writes should be no-ops since the existing key value should "win". If the network
1450 // partitions between datacenters A and B for 30 minutes, the database servers in
1451 // each datacenter will see an initial burst of writes with "old" timestamps via
1452 // replication. This might include writes with lower timestamps that the existing
1453 // key value. Therefore, clock skew and replication delay are both factors.
1454 $cutoffUnixSafe = (int)$this->getCurrentTime() - self::SAFE_PURGE_DELAY_SEC;
1455 $cutoffUnix = min( $cutoffUnix, $cutoffUnixSafe );
1456 }
1457 $tableIndexes = range( 0, $this->numTableShards - 1 );
1458 shuffle( $tableIndexes );
1459
1460 $batchSize = min( $this->writeBatchSize, $limit );
1461
1462 foreach ( $tableIndexes as $numShardsDone => $tableIndex ) {
1463 // The oldest expiry of a row we have deleted on this shard
1464 // (the first row that we deleted)
1465 $minExpUnix = null;
1466 // The most recent expiry time so far, from a row we have deleted on this shard
1467 $maxExp = null;
1468 // Size of the time range we'll delete, in seconds (for progress estimate)
1469 $totalSeconds = null;
1470
1471 do {
1472 $res = $db->newSelectQueryBuilder()
1473 ->select( [ 'keyname', 'exptime' ] )
1474 ->from( $this->getTableNameByShard( $tableIndex ) )
1475 ->where( $db->expr( 'exptime', '<', $db->timestamp( $cutoffUnix ) ) )
1476 ->andWhere( $maxExp ? $db->expr( 'exptime', '>=', $maxExp ) : [] )
1477 ->orderBy( 'exptime', SelectQueryBuilder::SORT_ASC )
1478 ->limit( $batchSize )
1479 ->caller( __METHOD__ )
1480 ->fetchResultSet();
1481
1482 if ( $res->numRows() ) {
1483 $row = $res->current();
1484 if ( $minExpUnix === null ) {
1485 $minExpUnix = (int)ConvertibleTimestamp::convert( TS_UNIX, $row->exptime );
1486 $totalSeconds = max( $cutoffUnix - $minExpUnix, 1 );
1487 }
1488
1489 $keys = [];
1490 foreach ( $res as $row ) {
1491 $keys[] = $row->keyname;
1492 $maxExp = $row->exptime;
1493 }
1494
1495 $db->newDeleteQueryBuilder()
1496 ->deleteFrom( $this->getTableNameByShard( $tableIndex ) )
1497 ->where( [
1498 'keyname' => $keys,
1499 $db->expr( 'exptime', '<', $db->timestamp( $cutoffUnix ) ),
1500 ] )
1501 ->caller( __METHOD__ )->execute();
1502 $keysDeletedCount += $db->affectedRows();
1503 }
1504
1505 if ( $progress && is_callable( $progress['fn'] ) ) {
1506 if ( $totalSeconds ) {
1507 $maxExpUnix = (int)ConvertibleTimestamp::convert( TS_UNIX, $maxExp );
1508 $remainingSeconds = $cutoffUnix - $maxExpUnix;
1509 $processedSeconds = max( $totalSeconds - $remainingSeconds, 0 );
1510 // For example, if we've done 1.5 table shard, and are thus half-way on the
1511 // 2nd of perhaps 5 tables on this server, then this might be:
1512 // `( 1 + ( 43200 / 86400 ) ) / 5 = 0.3`, or 30% done, of tables on this server.
1513 $tablesDoneRatio =
1514 ( $numShardsDone + ( $processedSeconds / $totalSeconds ) ) / $this->numTableShards;
1515 } else {
1516 $tablesDoneRatio = 1;
1517 }
1518
1519 // For example, if we're 30% done on the last of 10 servers, then this might be:
1520 // `( 9 / 10 ) + ( 0.3 / 10 ) = 0.93`, or 93% done, overall.
1521 $overallRatio = ( $progress['serversDone'] / $progress['serversTotal'] ) +
1522 ( $tablesDoneRatio / $progress['serversTotal'] );
1523 ( $progress['fn'] )( (int)( $overallRatio * 100 ) );
1524 }
1525 } while ( $res->numRows() && $keysDeletedCount < $limit );
1526 }
1527 }
1528
1529 /**
1530 * Delete content of shard tables in every server.
1531 * Return true if the operation is successful, false otherwise.
1532 *
1533 * @deprecated since 1.41, unused.
1534 *
1535 * @return bool
1536 */
1537 public function deleteAll() {
1538 wfDeprecated( __METHOD__, '1.41' );
1539 /** @noinspection PhpUnusedLocalVariableInspection */
1540 $silenceScope = $this->silenceTransactionProfiler();
1541 foreach ( $this->getShardServerIndexes() as $shardIndex ) {
1542 try {
1543 $db = $this->getConnection( $shardIndex );
1544 for ( $i = 0; $i < $this->numTableShards; $i++ ) {
1545 $db->newDeleteQueryBuilder()
1546 ->deleteFrom( $this->getTableNameByShard( $i ) )
1547 ->where( $db::ALL_ROWS )
1548 ->caller( __METHOD__ )->execute();
1549 }
1550 } catch ( DBError $e ) {
1551 $this->handleDBError( $e, $shardIndex );
1552 return false;
1553 }
1554 }
1555 return true;
1556 }
1557
1558 public function doLock( $key, $timeout = 6, $exptime = 6 ) {
1559 /** @noinspection PhpUnusedLocalVariableInspection */
1560 $silenceScope = $this->silenceTransactionProfiler();
1561
1562 $lockTsUnix = null;
1563
1564 [ $shardIndex ] = $this->getKeyLocation( $key );
1565 try {
1566 $db = $this->getConnection( $shardIndex );
1567 $lockTsUnix = $db->lock( $key, __METHOD__, $timeout, $db::LOCK_TIMESTAMP );
1568 } catch ( DBError $e ) {
1569 $this->handleDBError( $e, $shardIndex );
1570 $this->logger->warning(
1571 __METHOD__ . ' failed due to I/O error for {key}.',
1572 [ 'key' => $key ]
1573 );
1574 }
1575
1576 return $lockTsUnix;
1577 }
1578
1579 public function doUnlock( $key ) {
1580 /** @noinspection PhpUnusedLocalVariableInspection */
1581 $silenceScope = $this->silenceTransactionProfiler();
1582
1583 [ $shardIndex ] = $this->getKeyLocation( $key );
1584
1585 try {
1586 $db = $this->getConnection( $shardIndex );
1587 $released = $db->unlock( $key, __METHOD__ );
1588 } catch ( DBError $e ) {
1589 $this->handleDBError( $e, $shardIndex );
1590 $released = false;
1591 }
1592
1593 return $released;
1594 }
1595
1596 protected function makeKeyInternal( $keyspace, $components ) {
1597 // SQL schema for 'objectcache' specifies keys as varchar(255). From that,
1598 // subtract the number of characters we need for the keyspace and for
1599 // the separator character needed for each argument. To handle some
1600 // custom prefixes used by thing like WANObjectCache, limit to 205.
1601 $keyspace = strtr( $keyspace, ' ', '_' );
1602 $charsLeft = 205 - strlen( $keyspace ) - count( $components );
1603 foreach ( $components as &$component ) {
1604 $component = strtr( $component, [
1605 ' ' => '_', // Avoid unnecessary misses from pre-1.35 code
1606 ':' => '%3A',
1607 ] );
1608
1609 // 33 = 32 characters for the MD5 + 1 for the '#' prefix.
1610 if ( $charsLeft > 33 && strlen( $component ) > $charsLeft ) {
1611 $component = '#' . md5( $component );
1612 }
1613 $charsLeft -= strlen( $component );
1614 }
1615
1616 if ( $charsLeft < 0 ) {
1617 return $keyspace . ':BagOStuff-long-key:##' . md5( implode( ':', $components ) );
1618 }
1619 return $keyspace . ':' . implode( ':', $components );
1620 }
1621
1622 protected function requireConvertGenericKey(): bool {
1623 return true;
1624 }
1625
1626 protected function serialize( $value ) {
1627 if ( is_int( $value ) ) {
1628 return $value;
1629 }
1630
1631 $serial = serialize( $value );
1632 if ( $this->hasZlib ) {
1633 // On typical message and page data, this can provide a 3X storage savings
1634 $serial = gzdeflate( $serial );
1635 }
1636
1637 return $serial;
1638 }
1639
1640 protected function unserialize( $value ) {
1641 if ( $value === self::TOMB_SERIAL ) {
1642 return false; // tombstone
1643 }
1644
1645 if ( $this->isInteger( $value ) ) {
1646 return (int)$value;
1647 }
1648
1649 if ( $this->hasZlib ) {
1650 AtEase::suppressWarnings();
1651 $decompressed = gzinflate( $value );
1652 AtEase::restoreWarnings();
1653
1654 if ( $decompressed !== false ) {
1655 $value = $decompressed;
1656 }
1657 }
1658
1659 return unserialize( $value );
1660 }
1661
1662 private function getLoadBalancer(): ILoadBalancer {
1663 if ( !$this->loadBalancer ) {
1664 $this->loadBalancer = ( $this->loadBalancerCallback )();
1665 }
1666 return $this->loadBalancer;
1667 }
1668
1669 /**
1670 * @return IMaintainableDatabase
1671 * @throws DBError
1672 */
1673 private function getConnectionViaLoadBalancer() {
1674 $lb = $this->getLoadBalancer();
1675
1676 if ( $lb->getServerAttributes( ServerInfo::WRITER_INDEX )[Database::ATTR_DB_LEVEL_LOCKING] ) {
1677 // Use the main connection to avoid transaction deadlocks
1678 $conn = $lb->getMaintenanceConnectionRef( DB_PRIMARY, [], $this->dbDomain );
1679 } else {
1680 // If the RDBMS has row/table/page level locking, then use separate auto-commit
1681 // connection to avoid needless contention and deadlocks.
1682 $conn = $lb->getMaintenanceConnectionRef(
1683 DB_PRIMARY,
1684 [],
1685 $this->dbDomain,
1686 $lb::CONN_TRX_AUTOCOMMIT
1687 );
1688 }
1689
1690 // Make sure any errors are thrown now while we can more easily handle them
1691 $conn->ensureConnection();
1692 return $conn;
1693 }
1694
1695 /**
1696 * @param int $shardIndex
1697 * @param array $server Server config map
1698 * @return IMaintainableDatabase
1699 * @throws DBError
1700 */
1701 private function getConnectionFromServerInfo( $shardIndex, array $server ) {
1702 if ( !isset( $this->conns[$shardIndex] ) ) {
1703 $server['logger'] = $this->logger;
1704 // Always use autocommit mode, even if DBO_TRX is configured
1705 $server['flags'] ??= 0;
1706 $server['flags'] &= ~( IDatabase::DBO_TRX | IDatabase::DBO_DEFAULT );
1707
1708 /** @var IMaintainableDatabase $conn Auto-commit connection to the server */
1709 $conn = MediaWikiServices::getInstance()->getDatabaseFactory()
1710 ->create( $server['type'], $server );
1711
1712 // Automatically create the objectcache table for sqlite as needed
1713 if ( $conn->getType() === 'sqlite' ) {
1714 $this->initSqliteDatabase( $conn );
1715 }
1716 $this->conns[$shardIndex] = $conn;
1717 }
1718
1719 // @phan-suppress-next-line PhanTypeMismatchReturnNullable False positive
1720 return $this->conns[$shardIndex];
1721 }
1722
1723 /**
1724 * Handle a DBError which occurred during a read operation.
1725 *
1726 * @param DBError $exception
1727 * @param int $shardIndex Server index
1728 */
1729 private function handleDBError( DBError $exception, $shardIndex ) {
1730 if ( !$this->useLB && $exception instanceof DBConnectionError ) {
1731 unset( $this->conns[$shardIndex] ); // bug T103435
1732
1733 $now = $this->getCurrentTime();
1734 if ( isset( $this->connFailureTimes[$shardIndex] ) ) {
1735 if ( $now - $this->connFailureTimes[$shardIndex] >= 60 ) {
1736 unset( $this->connFailureTimes[$shardIndex] );
1737 unset( $this->connFailureErrors[$shardIndex] );
1738 } else {
1739 $this->logger->debug( __METHOD__ . ": Server #$shardIndex already down" );
1740 return;
1741 }
1742 }
1743 $this->logger->info( __METHOD__ . ": Server #$shardIndex down until " . ( $now + 60 ) );
1744 $this->connFailureTimes[$shardIndex] = $now;
1745 $this->connFailureErrors[$shardIndex] = $exception;
1746 }
1747 $this->logger->error( "DBError: {$exception->getMessage()}", [ 'exception' => $exception ] );
1748 if ( $exception instanceof DBConnectionError ) {
1749 $this->setLastError( self::ERR_UNREACHABLE );
1750 $this->logger->warning( __METHOD__ . ": ignoring connection error" );
1751 } else {
1752 $this->setLastError( self::ERR_UNEXPECTED );
1753 $this->logger->warning( __METHOD__ . ": ignoring query error" );
1754 }
1755 }
1756
1757 /**
1758 * @param IMaintainableDatabase $db
1759 * @throws DBError
1760 */
1761 private function initSqliteDatabase( IMaintainableDatabase $db ) {
1762 if ( $db->tableExists( 'objectcache', __METHOD__ ) ) {
1763 return;
1764 }
1765 // Use one table for SQLite; sharding does not seem to have much benefit
1766 $db->query( "PRAGMA journal_mode=WAL", __METHOD__ ); // this is permanent
1767 $db->startAtomic( __METHOD__ ); // atomic DDL
1768 try {
1769 $encTable = $db->tableName( 'objectcache' );
1770 $encExptimeIndex = $db->addIdentifierQuotes( $db->tablePrefix() . 'exptime' );
1771 $db->query(
1772 "CREATE TABLE $encTable (\n" .
1773 " keyname BLOB NOT NULL default '' PRIMARY KEY,\n" .
1774 " value BLOB,\n" .
1775 " exptime BLOB NOT NULL\n" .
1776 ")",
1777 __METHOD__
1778 );
1779 $db->query( "CREATE INDEX $encExptimeIndex ON $encTable (exptime)", __METHOD__ );
1780 $db->endAtomic( __METHOD__ );
1781 } catch ( DBError $e ) {
1782 $db->rollback( __METHOD__ );
1783 throw $e;
1784 }
1785 }
1786
1787 /**
1788 * Create the shard tables on all databases
1789 *
1790 * This is typically called manually by a sysadmin via eval.php, e.g. for ParserCache:
1791 *
1792 * @code
1793 * ObjectCache::getInstance( 'myparsercache' )->createTables();
1794 * @endcode
1795 *
1796 * This is different from `$services->getParserCache()->getCacheStorage()->createTables()`,
1797 * which would use the backend set via $wgParserCacheType, which shouldn't be
1798 * set yet for the backend you are creating shard tables on. The expectation
1799 * is to first add the new backend to $wgObjectCaches, run the above, and then enable
1800 * it for live ParserCache traffic by setting $wgParserCacheType.
1801 */
1802 public function createTables() {
1803 foreach ( $this->getShardServerIndexes() as $shardIndex ) {
1804 $db = $this->getConnection( $shardIndex );
1805 if ( in_array( $db->getType(), [ 'mysql', 'postgres' ], true ) ) {
1806 for ( $i = 0; $i < $this->numTableShards; $i++ ) {
1807 $encBaseTable = $db->tableName( 'objectcache' );
1808 $encShardTable = $db->tableName( $this->getTableNameByShard( $i ) );
1809 $db->query( "CREATE TABLE $encShardTable LIKE $encBaseTable", __METHOD__ );
1810 }
1811 }
1812 }
1813 }
1814
1815 /**
1816 * @return int[] List of server indexes
1817 */
1818 private function getShardServerIndexes() {
1819 if ( $this->useLB ) {
1820 // LoadBalancer based configuration
1821 $shardIndexes = [ 0 ];
1822 } else {
1823 // Striped array of database servers
1824 $shardIndexes = array_keys( $this->serverTags );
1825 }
1826
1827 return $shardIndexes;
1828 }
1829
1830 /**
1831 * Silence the transaction profiler until the return value falls out of scope
1832 *
1833 * @return ScopedCallback|null
1834 */
1835 private function silenceTransactionProfiler() {
1836 if ( $this->serverInfos ) {
1837 return null; // no TransactionProfiler injected anyway
1838 }
1839 return Profiler::instance()->getTransactionProfiler()->silenceForScope();
1840 }
1841 }