Merge "rest: Return a 400 for invalid render IDs"
[mediawiki.git] / includes / libs / objectcache / MediumSpecificBagOStuff.php
blob0391c402d261ace86941367a77fcf0ec10c9fe20
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
18 * @file
20 namespace Wikimedia\ObjectCache;
22 use InvalidArgumentException;
23 use JsonSerializable;
24 use stdClass;
25 use Wikimedia\WaitConditionLoop;
27 /**
28 * Helper classs that implements most of BagOStuff for a backend.
30 * This should be used by concrete implementations only. Wrapper classes that
31 * proxy another BagOStuff should extend and implement BagOStuff directly.
33 * @ingroup Cache
34 * @since 1.34
36 abstract class MediumSpecificBagOStuff extends BagOStuff {
37 /** @var array<string,array> Map of (key => (class LOCK_* constant => value) */
38 protected $locks = [];
39 /** @var int Bytes; chunk size of segmented cache values */
40 protected $segmentationSize;
41 /** @var int Bytes; maximum total size of a segmented cache value */
42 protected $segmentedValueMaxSize;
44 /** @var float Seconds; maximum expected seconds for a lock ping to reach the backend */
45 protected $maxLockSendDelay = 0.05;
47 /** @var array */
48 private $duplicateKeyLookups = [];
49 /** @var bool */
50 private $reportDupes = false;
51 /** @var bool */
52 private $dupeTrackScheduled = false;
54 /** Component to use for key construction of blob segment keys */
55 private const SEGMENT_COMPONENT = 'segment';
57 /** Idiom for doGet() to return extra information by reference */
58 protected const PASS_BY_REF = -1;
60 protected const METRIC_OP_GET = 'get';
61 protected const METRIC_OP_SET = 'set';
62 protected const METRIC_OP_DELETE = 'delete';
63 protected const METRIC_OP_CHANGE_TTL = 'change_ttl';
64 protected const METRIC_OP_ADD = 'add';
65 protected const METRIC_OP_INCR = 'incr';
66 protected const METRIC_OP_DECR = 'decr';
67 protected const METRIC_OP_CAS = 'cas';
69 protected const LOCK_RCLASS = 0;
70 protected const LOCK_DEPTH = 1;
71 protected const LOCK_TIME = 2;
72 protected const LOCK_EXPIRY = 3;
74 /**
75 * @see BagOStuff::__construct()
76 * Additional $params options include:
77 * - logger: Psr\Log\LoggerInterface instance
78 * - reportDupes: Whether to emit warning log messages for all keys that were
79 * requested more than once (requires an asyncHandler).
80 * - segmentationSize: The chunk size, in bytes, of segmented values. The value should
81 * not exceed the maximum size of values in the storage backend, as configured by
82 * the site administrator.
83 * - segmentedValueMaxSize: The maximum total size, in bytes, of segmented values.
84 * This should be configured to a reasonable size give the site traffic and the
85 * amount of I/O between application and cache servers that the network can handle.
87 * @param array $params
89 * @phpcs:ignore Generic.Files.LineLength
90 * @phan-param array{logger?:\Psr\Log\LoggerInterface,asyncHandler?:callable,reportDupes?:bool,segmentationSize?:int|float,segmentedValueMaxSize?:int} $params
92 public function __construct( array $params = [] ) {
93 parent::__construct( $params );
95 if ( !empty( $params['reportDupes'] ) && $this->asyncHandler ) {
96 $this->reportDupes = true;
99 // Default to 8MiB if segmentationSize is not set
100 $this->segmentationSize = $params['segmentationSize'] ?? 8_388_608;
101 // Default to 64MiB if segmentedValueMaxSize is not set
102 $this->segmentedValueMaxSize = $params['segmentedValueMaxSize'] ?? 67_108_864;
106 * Get an item with the given key
108 * If the key includes a deterministic input hash (e.g. the key can only have
109 * the correct value) or complete staleness checks are handled by the caller
110 * (e.g. nothing relies on the TTL), then the READ_VERIFIED flag should be set.
111 * This lets tiered backends know they can safely upgrade a cached value to
112 * higher tiers using standard TTLs.
114 * @param string $key
115 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
117 * @return mixed Returns false on failure or if the item does not exist
119 public function get( $key, $flags = 0 ) {
120 $this->trackDuplicateKeys( $key );
122 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
126 * Track the number of times that a given key has been used.
128 * @param string $key
130 private function trackDuplicateKeys( $key ) {
131 if ( !$this->reportDupes ) {
132 return;
135 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
136 // Track that we have seen this key. This N-1 counting style allows
137 // easy filtering with array_filter() later.
138 $this->duplicateKeyLookups[$key] = 0;
139 } else {
140 $this->duplicateKeyLookups[$key]++;
142 if ( $this->dupeTrackScheduled === false ) {
143 $this->dupeTrackScheduled = true;
144 // Schedule a callback that logs keys processed more than once by get().
145 call_user_func( $this->asyncHandler, function () {
146 $dups = array_filter( $this->duplicateKeyLookups );
147 foreach ( $dups as $key => $count ) {
148 $this->logger->warning(
149 'Duplicate get(): "{key}" fetched {count} times',
150 // Count is N-1 of the actual lookup count
151 [ 'key' => $key, 'count' => $count + 1, ]
154 } );
160 * Get an item
162 * The CAS token should be null if the key does not exist or the value is corrupt
164 * @param string $key
165 * @param int $flags Bitfield of BagOStuff::READ_* constants [optional]
166 * @param mixed &$casToken CAS token if MediumSpecificBagOStuff::PASS_BY_REF [returned]
168 * @return mixed Returns false on failure or if the item does not exist
170 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
172 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
173 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
175 // Only when all segments (if any) are stored should the main key be changed
176 return $ok && $this->doSet( $key, $entry, $exptime, $flags );
180 * Set an item
182 * @param string $key
183 * @param mixed $value
184 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
185 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
187 * @return bool Success
189 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
191 public function delete( $key, $flags = 0 ) {
192 if ( !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
193 return $this->doDelete( $key, $flags );
196 $mainValue = $this->doGet( $key, self::READ_LATEST );
197 if ( !$this->doDelete( $key, $flags ) ) {
198 return false;
201 if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
202 // no segments to delete
203 return true;
206 $orderedKeys = array_map(
207 function ( $segmentHash ) use ( $key ) {
208 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
210 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
213 return $this->deleteMulti( $orderedKeys, $flags & ~self::WRITE_ALLOW_SEGMENTS );
217 * Delete an item
219 * @param string $key
220 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
222 * @return bool True if the item was deleted or not found, false on failure
224 abstract protected function doDelete( $key, $flags = 0 );
226 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
227 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
229 // Only when all segments (if any) are stored should the main key be changed
230 return $ok && $this->doAdd( $key, $entry, $exptime, $flags );
234 * Insert an item if it does not already exist
236 * @param string $key
237 * @param mixed $value
238 * @param int $exptime
239 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
241 * @return bool Success
243 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
246 * Merge changes into the existing cache value (possibly creating a new one)
248 * The callback function returns the new value given the current value
249 * (which will be false if not present), and takes the arguments:
250 * (this BagOStuff, cache key, current value, TTL).
251 * The TTL parameter is reference set to $exptime. It can be overridden in the callback.
252 * Nothing is stored nor deleted if the callback returns false.
254 * @param string $key
255 * @param callable $callback Callback method to be executed
256 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
257 * @param int $attempts The amount of times to attempt a merge in case of failure
258 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
260 * @return bool Success
262 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
263 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
267 * @param string $key
268 * @param callable $callback Callback method to be executed
269 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
270 * @param int $attempts The amount of times to attempt a merge in case of failure
271 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
273 * @return bool Success
274 * @see BagOStuff::merge()
276 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
277 $attemptsLeft = $attempts;
278 do {
279 $token = self::PASS_BY_REF;
280 // Get the old value and CAS token from cache
281 $watchPoint = $this->watchErrors();
282 $currentValue = $this->resolveSegments(
283 $key,
284 $this->doGet( $key, $flags, $token )
286 if ( $this->getLastError( $watchPoint ) ) {
287 // Don't spam slow retries due to network problems (retry only on races)
288 $this->logger->warning(
289 __METHOD__ . ' failed due to read I/O error on get() for {key}.', [ 'key' => $key ]
291 $success = false;
292 break;
295 // Derive the new value from the old value
296 $value = $callback( $this, $key, $currentValue, $exptime );
297 $keyWasNonexistent = ( $currentValue === false );
298 $valueMatchesOldValue = ( $value === $currentValue );
299 // free RAM in case the value is large
300 unset( $currentValue );
302 $watchPoint = $this->watchErrors();
303 if ( $value === false || $exptime < 0 ) {
304 // do nothing
305 $success = true;
306 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
307 // recently set by another thread to the same value
308 $success = true;
309 } elseif ( $keyWasNonexistent ) {
310 // Try to create the key, failing if it gets created in the meantime
311 $success = $this->add( $key, $value, $exptime, $flags );
312 } else {
313 // Try to update the key, failing if it gets changed in the meantime
314 $success = $this->cas( $token, $key, $value, $exptime, $flags );
316 if ( $this->getLastError( $watchPoint ) ) {
317 // Don't spam slow retries due to network problems (retry only on races)
318 $this->logger->warning(
319 __METHOD__ . ' failed due to write I/O error for {key}.',
320 [ 'key' => $key ]
322 $success = false;
323 break;
326 } while ( !$success && --$attemptsLeft );
328 return $success;
332 * Set an item if the current CAS token matches the provided CAS token
334 * @param mixed $casToken Only set the item if it still has this CAS token
335 * @param string $key
336 * @param mixed $value
337 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
338 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
340 * @return bool Success
342 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
343 if ( $casToken === null ) {
344 $this->logger->warning(
345 __METHOD__ . ' got empty CAS token for {key}.',
346 [ 'key' => $key ]
349 // caller may have meant to use add()?
350 return false;
353 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
355 // Only when all segments (if any) are stored should the main key be changed
356 return $ok && $this->doCas( $casToken, $key, $entry, $exptime, $flags );
360 * Set an item if the current CAS token matches the provided CAS token
362 * @param mixed $casToken CAS token from an existing version of the key
363 * @param string $key
364 * @param mixed $value
365 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
366 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
368 * @return bool Success
370 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
371 // @TODO: the use of lock() assumes that all other relevant sets() use a lock
372 if ( !$this->lock( $key, 0 ) ) {
373 // non-blocking
374 return false;
377 $curCasToken = self::PASS_BY_REF;
378 $watchPoint = $this->watchErrors();
379 $exists = ( $this->doGet( $key, self::READ_LATEST, $curCasToken ) !== false );
380 if ( $this->getLastError( $watchPoint ) ) {
381 // Fail if the old CAS token could not be read
382 $success = false;
383 $this->logger->warning(
384 __METHOD__ . ' failed due to write I/O error for {key}.',
385 [ 'key' => $key ]
387 } elseif ( $exists && $this->tokensMatch( $casToken, $curCasToken ) ) {
388 $success = $this->doSet( $key, $value, $exptime, $flags );
389 } else {
390 // mismatched or failed
391 $success = false;
392 $this->logger->info(
393 __METHOD__ . ' failed due to race condition for {key}.',
394 [ 'key' => $key, 'key_exists' => $exists ]
398 $this->unlock( $key );
400 return $success;
404 * @param mixed $value CAS token for an existing key
405 * @param mixed $otherValue CAS token for an existing key
407 * @return bool Whether the two tokens match
409 final protected function tokensMatch( $value, $otherValue ) {
410 $type = gettype( $value );
411 // Ideally, tokens are counters, timestamps, hashes, or serialized PHP values.
412 // However, some classes might use the PHP values themselves.
413 if ( $type !== gettype( $otherValue ) ) {
414 return false;
416 // Serialize both tokens to strictly compare objects or arrays (which might objects
417 // nested inside). Note that this will not apply if integer/string CAS tokens are used.
418 if ( $type === 'array' || $type === 'object' ) {
419 return ( serialize( $value ) === serialize( $otherValue ) );
422 // For string/integer tokens, use a simple comparison
423 return ( $value === $otherValue );
427 * Change the expiration on a key if it exists
429 * If an expiry in the past is given then the key will immediately be expired
431 * For large values written using WRITE_ALLOW_SEGMENTS, this only changes the TTL of the
432 * main segment list key. While lowering the TTL of the segment list key has the effect of
433 * functionally lowering the TTL of the key, it might leave unused blobs in cache for longer.
434 * Raising the TTL of such keys is not effective, since the expiration of a single segment
435 * key effectively expires the entire value.
437 * @param string $key
438 * @param int $exptime TTL or UNIX timestamp
439 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
441 * @return bool Success Returns false on failure or if the item does not exist
442 * @since 1.28
444 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
445 return $this->doChangeTTL( $key, $exptime, $flags );
449 * @param string $key
450 * @param int $exptime
451 * @param int $flags
453 * @return bool
455 protected function doChangeTTL( $key, $exptime, $flags ) {
456 // @TODO: the use of lock() assumes that all other relevant sets() use a lock
457 if ( !$this->lock( $key, 0 ) ) {
458 return false;
461 $expiry = $this->getExpirationAsTimestamp( $exptime );
462 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
464 // Use doGet() to avoid having to trigger resolveSegments()
465 $blob = $this->doGet( $key, self::READ_LATEST );
466 if ( $blob ) {
467 if ( $delete ) {
468 $ok = $this->doDelete( $key, $flags );
469 } else {
470 $ok = $this->doSet( $key, $blob, $exptime, $flags );
472 } else {
473 $ok = false;
476 $this->unlock( $key );
478 return $ok;
481 public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 ) {
482 $step = (int)$step;
483 $init = is_int( $init ) ? $init : $step;
485 return $this->doIncrWithInit( $key, $exptime, $step, $init, $flags );
489 * @param string $key
490 * @param int $exptime
491 * @param int $step
492 * @param int $init
493 * @param int $flags
495 * @return int|bool New value or false on failure
497 abstract protected function doIncrWithInit( $key, $exptime, $step, $init, $flags );
500 * @param string $key
501 * @param int $timeout
502 * @param int $exptime
503 * @param string $rclass
505 * @return bool
507 public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' ) {
508 $exptime = min( $exptime ?: INF, self::TTL_DAY );
510 $acquired = false;
512 if ( isset( $this->locks[$key] ) ) {
513 // Already locked; avoid deadlocks and allow lock reentry if specified
514 if ( $rclass != '' && $this->locks[$key][self::LOCK_RCLASS] === $rclass ) {
515 ++$this->locks[$key][self::LOCK_DEPTH];
516 $acquired = true;
518 } else {
519 // Not already locked; acquire a lock on the backend
520 $lockTsUnix = $this->doLock( $key, $timeout, $exptime );
521 if ( $lockTsUnix !== null ) {
522 $this->locks[$key] = [
523 self::LOCK_RCLASS => $rclass,
524 self::LOCK_DEPTH => 1,
525 self::LOCK_TIME => $lockTsUnix,
526 self::LOCK_EXPIRY => $lockTsUnix + $exptime
528 $acquired = true;
532 return $acquired;
536 * @see MediumSpecificBagOStuff::lock()
538 * @param string $key
539 * @param int $timeout Lock wait timeout; 0 for non-blocking [optional]
540 * @param int $exptime Lock time-to-live 1 day maximum [optional]
542 * @return float|null UNIX timestamp of acquisition; null on failure
544 protected function doLock( $key, $timeout, $exptime ) {
545 $lockTsUnix = null;
547 $fname = __METHOD__;
548 $loop = new WaitConditionLoop(
549 function () use ( $key, $exptime, $fname, &$lockTsUnix ) {
550 $watchPoint = $this->watchErrors();
551 if ( $this->add( $this->makeLockKey( $key ), 1, $exptime ) ) {
552 $lockTsUnix = microtime( true );
554 return WaitConditionLoop::CONDITION_REACHED;
555 } elseif ( $this->getLastError( $watchPoint ) ) {
556 $this->logger->warning(
557 "$fname failed due to I/O error for {key}.",
558 [ 'key' => $key ]
561 return WaitConditionLoop::CONDITION_ABORTED;
564 return WaitConditionLoop::CONDITION_CONTINUE;
566 $timeout
568 $code = $loop->invoke();
570 if ( $code === $loop::CONDITION_TIMED_OUT ) {
571 $this->logger->warning(
572 "$fname failed due to timeout for {key}.",
573 [ 'key' => $key, 'timeout' => $timeout ]
577 return $lockTsUnix;
581 * Release an advisory lock on a key string
583 * @param string $key
585 * @return bool Success
587 public function unlock( $key ) {
588 $released = false;
590 if ( isset( $this->locks[$key] ) ) {
591 if ( --$this->locks[$key][self::LOCK_DEPTH] > 0 ) {
592 $released = true;
593 } else {
594 $released = $this->doUnlock( $key );
595 unset( $this->locks[$key] );
596 if ( !$released ) {
597 $this->logger->warning(
598 __METHOD__ . ' failed to release lock for {key}.',
599 [ 'key' => $key ]
603 } else {
604 $this->logger->warning(
605 __METHOD__ . ' no lock to release for {key}.',
606 [ 'key' => $key ]
610 return $released;
614 * @see MediumSpecificBagOStuff::unlock()
616 * @param string $key
618 * @return bool Success
620 protected function doUnlock( $key ) {
621 $released = false;
623 // Estimate the remaining TTL of the lock key
624 $curTTL = $this->locks[$key][self::LOCK_EXPIRY] - $this->getCurrentTime();
626 // Check the risk of race conditions for key deletion
627 if ( $this->getQoS( self::ATTR_DURABILITY ) <= self::QOS_DURABILITY_SCRIPT ) {
628 // Lock (and data) keys use memory specific to this request (e.g. HashBagOStuff)
629 $isSafe = true;
630 } else {
631 // It is unsafe to delete the lock key if there is a serious risk of the key already
632 // being claimed by another thread before the delete operation reaches the backend
633 $isSafe = ( $curTTL > $this->maxLockSendDelay );
636 if ( $isSafe ) {
637 $released = $this->doDelete( $this->makeLockKey( $key ) );
638 } else {
639 $this->logger->warning(
640 "Lock for {key} held too long ({age} sec).",
641 [ 'key' => $key, 'curTTL' => $curTTL ]
645 return $released;
649 * @param string $key
651 * @return string
653 protected function makeLockKey( $key ) {
654 return "$key:lock";
657 public function deleteObjectsExpiringBefore(
658 $timestamp,
659 ?callable $progress = null,
660 $limit = INF,
661 ?string $tag = null
663 return false;
667 * Get an associative array containing the item for each of the keys that have items.
669 * @param string[] $keys List of keys; can be a map of (unused => key) for convenience
670 * @param int $flags Bitfield; supports READ_LATEST [optional]
672 * @return mixed[] Map of (key => value) for existing keys; preserves the order of $keys
674 public function getMulti( array $keys, $flags = 0 ) {
675 $foundByKey = $this->doGetMulti( $keys, $flags );
677 $res = [];
678 foreach ( $keys as $key ) {
679 // Resolve one blob at a time (avoids too much I/O at once)
680 if ( array_key_exists( $key, $foundByKey ) ) {
681 // A value should not appear in the key if a segment is missing
682 $value = $this->resolveSegments( $key, $foundByKey[$key] );
683 if ( $value !== false ) {
684 $res[$key] = $value;
689 return $res;
693 * Get an associative array containing the item for each of the keys that have items.
695 * @param string[] $keys List of keys
696 * @param int $flags Bitfield; supports READ_LATEST [optional]
698 * @return array Map of (key => value) for existing keys; preserves the order of $keys
700 protected function doGetMulti( array $keys, $flags = 0 ) {
701 $res = [];
702 foreach ( $keys as $key ) {
703 $val = $this->doGet( $key, $flags );
704 if ( $val !== false ) {
705 $res[$key] = $val;
709 return $res;
713 * Batch insertion/replace
715 * This does not support WRITE_ALLOW_SEGMENTS to avoid excessive read I/O
717 * @param mixed[] $valueByKey Map of (key => value)
718 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
719 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
721 * @return bool Success
722 * @since 1.24
724 public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) {
725 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
726 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
729 return $this->doSetMulti( $valueByKey, $exptime, $flags );
733 * @param mixed[] $data Map of (key => value)
734 * @param int $exptime Either an interval in seconds or a unix timestamp for expiry
735 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
737 * @return bool Success
739 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
740 $res = true;
741 foreach ( $data as $key => $value ) {
742 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
745 return $res;
748 public function deleteMulti( array $keys, $flags = 0 ) {
749 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
750 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
753 return $this->doDeleteMulti( $keys, $flags );
757 * @param string[] $keys List of keys
758 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
760 * @return bool Success
762 protected function doDeleteMulti( array $keys, $flags = 0 ) {
763 $res = true;
764 foreach ( $keys as $key ) {
765 $res = $this->doDelete( $key, $flags ) && $res;
768 return $res;
772 * Change the expiration of multiple keys that exist
774 * @param string[] $keys List of keys
775 * @param int $exptime TTL or UNIX timestamp
776 * @param int $flags Bitfield of BagOStuff::WRITE_* constants (since 1.33)
778 * @return bool Success
780 * @since 1.34
782 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
783 return $this->doChangeTTLMulti( $keys, $exptime, $flags );
787 * @param string[] $keys List of keys
788 * @param int $exptime TTL or UNIX timestamp
789 * @param int $flags Bitfield of BagOStuff::WRITE_* constants
791 * @return bool Success
793 protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
794 $res = true;
795 foreach ( $keys as $key ) {
796 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
799 return $res;
803 * Get and reassemble the chunks of blob at the given key
805 * @param string $key
806 * @param mixed $mainValue
808 * @return string|null|bool The combined string, false if missing, null on error
810 final protected function resolveSegments( $key, $mainValue ) {
811 if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
812 $orderedKeys = array_map(
813 function ( $segmentHash ) use ( $key ) {
814 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
816 $mainValue->{SerializedValueContainer::SEGMENTED_HASHES}
819 $segmentsByKey = $this->doGetMulti( $orderedKeys );
821 $parts = [];
822 foreach ( $orderedKeys as $segmentKey ) {
823 if ( isset( $segmentsByKey[$segmentKey] ) ) {
824 $parts[] = $segmentsByKey[$segmentKey];
825 } else {
826 // missing segment
827 return false;
831 return $this->unserialize( implode( '', $parts ) );
834 return $mainValue;
838 * Check if a value should use a segmentation wrapper due to its size
840 * In order to avoid extra serialization and/or twice-serialized wrappers, just check if
841 * the value is a large string. Support cache wrappers (e.g. WANObjectCache) that use 2D
842 * arrays to wrap values. This does not recurse in order to avoid overhead from complex
843 * structures and the risk of infinite loops (due to references).
845 * @param mixed $value
846 * @param int $flags
848 * @return bool
850 private function useSegmentationWrapper( $value, $flags ) {
851 if (
852 $this->segmentationSize === INF ||
853 !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS )
855 return false;
858 if ( is_string( $value ) ) {
859 return ( strlen( $value ) >= $this->segmentationSize );
862 if ( is_array( $value ) ) {
863 // Expect that the contained value will be one of the first array entries
864 foreach ( array_slice( $value, 0, 4 ) as $v ) {
865 if ( is_string( $v ) && strlen( $v ) >= $this->segmentationSize ) {
866 return true;
871 // Avoid breaking functions for incrementing/decrementing integer key values
872 return false;
876 * Make the entry to store at a key (inline or segment list), storing any segments
878 * @param string $key
879 * @param mixed $value
880 * @param int $exptime
881 * @param int $flags
882 * @param mixed|null &$ok Whether the entry is usable (e.g. no missing segments) [returned]
884 * @return mixed The entry (inline value, wrapped inline value, or wrapped segment list)
885 * @since 1.34
887 final protected function makeValueOrSegmentList( $key, $value, $exptime, $flags, &$ok ) {
888 $entry = $value;
889 $ok = true;
891 if ( $this->useSegmentationWrapper( $value, $flags ) ) {
892 $segmentSize = $this->segmentationSize;
893 $maxTotalSize = $this->segmentedValueMaxSize;
894 $serialized = $this->getSerialized( $value, $key );
895 $size = strlen( $serialized );
896 if ( $size > $maxTotalSize ) {
897 $this->logger->warning(
898 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
899 [ 'key' => $key ]
901 } else {
902 // Split the serialized value into chunks and store them at different keys
903 $chunksByKey = [];
904 $segmentHashes = [];
905 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
906 for ( $i = 0; $i < $count; ++$i ) {
907 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
908 $hash = sha1( $segment );
909 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
910 $chunksByKey[$chunkKey] = $segment;
911 $segmentHashes[] = $hash;
913 $flags &= ~self::WRITE_ALLOW_SEGMENTS;
914 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
915 $entry = SerializedValueContainer::newSegmented( $segmentHashes );
919 return $entry;
923 * @param int|float $exptime
925 * @return bool Whether the expiry is non-infinite, and, negative or not a UNIX timestamp
926 * @since 1.34
928 final protected function isRelativeExpiration( $exptime ) {
929 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
933 * Convert an optionally relative timestamp to an absolute time
935 * The input value will be cast to an integer and interpreted as follows:
936 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
937 * - negative: relative TTL; return UNIX timestamp offset by this value
938 * - positive (< 10 years): relative TTL; return UNIX timestamp offset by this value
939 * - positive (>= 10 years): absolute UNIX timestamp; return this value
941 * @param int $exptime
943 * @return int Expiration timestamp or TTL_INDEFINITE for indefinite
944 * @since 1.34
946 final protected function getExpirationAsTimestamp( $exptime ) {
947 if ( $exptime == self::TTL_INDEFINITE ) {
948 return $exptime;
951 return $this->isRelativeExpiration( $exptime )
952 ? intval( $this->getCurrentTime() + $exptime )
953 : $exptime;
957 * Convert an optionally absolute expiry time to a relative time. If an
958 * absolute time is specified which is in the past, use a short expiry time.
960 * The input value will be cast to an integer and interpreted as follows:
961 * - zero: no expiry; return zero (e.g. TTL_INDEFINITE)
962 * - negative: relative TTL; return a short expiry time (1 second)
963 * - positive (< 10 years): relative TTL; return this value
964 * - positive (>= 10 years): absolute UNIX timestamp; return offset to current time
966 * @param int $exptime
968 * @return int Relative TTL or TTL_INDEFINITE for indefinite
969 * @since 1.34
971 final protected function getExpirationAsTTL( $exptime ) {
972 if ( $exptime == self::TTL_INDEFINITE ) {
973 return $exptime;
976 return $this->isRelativeExpiration( $exptime )
977 ? $exptime
978 : (int)max( $exptime - $this->getCurrentTime(), 1 );
982 * Check if a value is an integer
984 * @param mixed $value
986 * @return bool
988 final protected function isInteger( $value ) {
989 if ( is_int( $value ) ) {
990 return true;
991 } elseif ( !is_string( $value ) ) {
992 return false;
995 $integer = (int)$value;
997 return ( $value === (string)$integer );
1000 public function getQoS( $flag ) {
1001 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
1005 * @deprecated since 1.43, not used anywhere.
1007 public function getSegmentationSize() {
1008 wfDeprecated( __METHOD__, '1.43' );
1010 return $this->segmentationSize;
1014 * @deprecated since 1.43, not used anywhere.
1016 public function getSegmentedValueMaxSize() {
1017 wfDeprecated( __METHOD__, '1.43' );
1019 return $this->segmentedValueMaxSize;
1023 * Get the serialized form a value, logging a warning if it involves custom classes
1025 * @param mixed $value
1026 * @param string $key
1028 * @return string|int String/integer representation of value
1029 * @since 1.35
1031 protected function getSerialized( $value, $key ) {
1032 $this->checkValueSerializability( $value, $key );
1034 return $this->serialize( $value );
1038 * Log if a new cache value does not appear suitable for serialization at a quick glance
1040 * This aids migration of values to JSON-like structures and the debugging of exceptions
1041 * due to serialization failure.
1043 * This does not recurse more than one level into container structures.
1045 * A proper cache key value is one of the following:
1046 * - null
1047 * - a scalar
1048 * - an array with scalar/null values
1049 * - an array tree with scalar/null "leaf" values
1050 * - an stdClass instance with scalar/null field values
1051 * - an stdClass instance tree with scalar/null "leaf" values
1052 * - an instance of a class that implements JsonSerializable
1054 * @param mixed $value Result of the value generation callback for the key
1055 * @param string $key Cache key
1057 private function checkValueSerializability( $value, $key ) {
1058 if ( is_array( $value ) ) {
1059 $this->checkIterableMapSerializability( $value, $key );
1060 } elseif ( is_object( $value ) ) {
1061 // Note that Closure instances count as objects
1062 if ( $value instanceof stdClass ) {
1063 $this->checkIterableMapSerializability( $value, $key );
1064 } elseif ( !( $value instanceof JsonSerializable ) ) {
1065 $this->logger->warning(
1066 "{class} value for '{cachekey}'; serialization is suspect.",
1067 [ 'cachekey' => $key, 'class' => get_class( $value ) ]
1074 * @param array|stdClass $value Result of the value generation callback for the key
1075 * @param string $key Cache key
1077 private function checkIterableMapSerializability( $value, $key ) {
1078 foreach ( $value as $index => $entry ) {
1079 if ( is_object( $entry ) ) {
1080 // Note that Closure instances count as objects
1081 if (
1082 !( $entry instanceof \stdClass ) &&
1083 !( $entry instanceof \JsonSerializable )
1085 $this->logger->warning(
1086 "{class} value for '{cachekey}' at '$index'; serialization is suspect.",
1087 [ 'cachekey' => $key, 'class' => get_class( $entry ) ]
1090 return;
1097 * @param mixed $value
1099 * @return string|int|false String/integer representation
1100 * @note Special handling is usually needed for integers so incr()/decr() work
1102 protected function serialize( $value ) {
1103 return is_int( $value ) ? $value : serialize( $value );
1107 * @param string|int|false $value
1109 * @return mixed Original value or false on error
1110 * @note Special handling is usually needed for integers so incr()/decr() work
1112 protected function unserialize( $value ) {
1113 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1117 * @param string $text
1119 protected function debug( $text ) {
1120 $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] );
1124 * @param string $key Key generated by BagOStuff::makeKeyInternal
1126 * @return string A stats prefix to describe this class of key (e.g. "objectcache.file")
1128 private function determinekeyGroupForStats( $key ): string {
1129 // Key came directly from BagOStuff::makeKey() or BagOStuff::makeGlobalKey()
1130 // and thus has the format of "<scope>:<collection>[:<constant or variable>]..."
1131 $components = explode( ':', $key, 3 );
1132 // Handle legacy callers that fail to use the key building methods
1133 $keygroup = $components[1] ?? 'UNKNOWN';
1135 return strtr( $keygroup, '.', '_' );
1139 * @param string $op Operation name as a MediumSpecificBagOStuff::METRIC_OP_* constant
1140 * @param array<int,string>|array<string,int[]> $keyInfo Key list, if payload sizes are not
1141 * applicable, otherwise, map of (key => (send payload size, receive payload size)); send
1142 * and receive sizes are 0 where not applicable and receive sizes are "false" for keys
1143 * that were not found during read operations
1145 protected function updateOpStats( string $op, array $keyInfo ) {
1146 $deltasByMetric = [];
1148 foreach ( $keyInfo as $indexOrKey => $keyOrSizes ) {
1149 if ( is_array( $keyOrSizes ) ) {
1150 $key = $indexOrKey;
1151 [ $sPayloadSize, $rPayloadSize ] = $keyOrSizes;
1152 } else {
1153 $key = $keyOrSizes;
1154 $sPayloadSize = 0;
1155 $rPayloadSize = 0;
1158 // Metric prefix for the cache wrapper and key collection name
1159 $keygroup = $this->determinekeyGroupForStats( $key );
1161 if ( $op === self::METRIC_OP_GET ) {
1162 // This operation was either a "hit" or "miss" for this key
1163 if ( $rPayloadSize === false ) {
1164 $statsdName = "objectcache.{$keygroup}.{$op}_miss_rate";
1165 $statsName = "bagostuff_miss_total";
1166 } else {
1167 $statsdName = "objectcache.{$keygroup}.{$op}_hit_rate";
1168 $statsName = "bagostuff_hit_total";
1170 } else {
1171 // There is no concept of "hit" or "miss" for this operation
1172 $statsdName = "objectcache.{$keygroup}.{$op}_call_rate";
1173 $statsName = "bagostuff_call_total";
1175 $deltasByMetric[$statsdName] = [
1176 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + 1,
1177 'metric' => $statsName,
1178 'keygroup' => $keygroup,
1179 'operation' => $op,
1182 if ( $sPayloadSize > 0 ) {
1183 $statsdName = "objectcache.{$keygroup}.{$op}_bytes_sent";
1184 $statsName = "bagostuff_bytes_sent_total";
1185 $deltasByMetric[$statsdName] = [
1186 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + $sPayloadSize,
1187 'metric' => $statsName,
1188 'keygroup' => $keygroup,
1189 'operation' => $op,
1193 if ( $rPayloadSize > 0 ) {
1194 $statsdName = "objectcache.{$keygroup}.{$op}_bytes_read";
1195 $statsName = "bagostuff_bytes_read_total";
1196 $deltasByMetric[$statsdName] = [
1197 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + $rPayloadSize,
1198 'metric' => $statsName,
1199 'keygroup' => $keygroup,
1200 'operation' => $op,
1205 foreach ( $deltasByMetric as $statsdName => $delta ) {
1206 $this->stats->getCounter( $delta['metric'] )
1207 ->setLabel( 'keygroup', $delta['keygroup'] )
1208 ->setLabel( 'operation', $delta['operation'] )
1209 ->copyToStatsdAt( $statsdName )
1210 ->incrementBy( $delta['delta'] );
1215 /** @deprecated class alias since 1.43 */
1216 class_alias( MediumSpecificBagOStuff::class, 'MediumSpecificBagOStuff' );