MediaWiki master
MediumSpecificBagOStuff.php
Go to the documentation of this file.
1<?php
24namespace Wikimedia\ObjectCache;
25
26use InvalidArgumentException;
27use JsonSerializable;
29use stdClass;
30use Wikimedia\WaitConditionLoop;
31
40abstract class MediumSpecificBagOStuff extends BagOStuff {
42 protected $locks = [];
47
49 protected $maxLockSendDelay = 0.05;
50
52 private $duplicateKeyLookups = [];
54 private $reportDupes = false;
56 private $dupeTrackScheduled = false;
57
59 private const SEGMENT_COMPONENT = 'segment';
60
62 protected const PASS_BY_REF = -1;
63
64 protected const METRIC_OP_GET = 'get';
65 protected const METRIC_OP_SET = 'set';
66 protected const METRIC_OP_DELETE = 'delete';
67 protected const METRIC_OP_CHANGE_TTL = 'change_ttl';
68 protected const METRIC_OP_ADD = 'add';
69 protected const METRIC_OP_INCR = 'incr';
70 protected const METRIC_OP_DECR = 'decr';
71 protected const METRIC_OP_CAS = 'cas';
72
73 protected const LOCK_RCLASS = 0;
74 protected const LOCK_DEPTH = 1;
75 protected const LOCK_TIME = 2;
76 protected const LOCK_EXPIRY = 3;
77
96 public function __construct( array $params = [] ) {
97 parent::__construct( $params );
98
99 if ( !empty( $params['reportDupes'] ) && $this->asyncHandler ) {
100 $this->reportDupes = true;
101 }
102
103 // Default to 8MiB if segmentationSize is not set
104 $this->segmentationSize = $params['segmentationSize'] ?? 8_388_608;
105 // Default to 64MiB if segmentedValueMaxSize is not set
106 $this->segmentedValueMaxSize = $params['segmentedValueMaxSize'] ?? 67_108_864;
107 }
108
123 public function get( $key, $flags = 0 ) {
124 $this->trackDuplicateKeys( $key );
125
126 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
127 }
128
134 private function trackDuplicateKeys( $key ) {
135 if ( !$this->reportDupes ) {
136 return;
137 }
138
139 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
140 // Track that we have seen this key. This N-1 counting style allows
141 // easy filtering with array_filter() later.
142 $this->duplicateKeyLookups[$key] = 0;
143 } else {
144 $this->duplicateKeyLookups[$key] += 1;
145
146 if ( $this->dupeTrackScheduled === false ) {
147 $this->dupeTrackScheduled = true;
148 // Schedule a callback that logs keys processed more than once by get().
149 call_user_func( $this->asyncHandler, function () {
150 $dups = array_filter( $this->duplicateKeyLookups );
151 foreach ( $dups as $key => $count ) {
152 $this->logger->warning(
153 'Duplicate get(): "{key}" fetched {count} times',
154 // Count is N-1 of the actual lookup count
155 [ 'key' => $key, 'count' => $count + 1, ]
156 );
157 }
158 } );
159 }
160 }
161 }
162
174 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
175
186 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
187 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
188
189 // Only when all segments (if any) are stored should the main key be changed
190 return $ok && $this->doSet( $key, $entry, $exptime, $flags );
191 }
192
203 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
204
217 public function delete( $key, $flags = 0 ) {
218 if ( !$this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
219 return $this->doDelete( $key, $flags );
220 }
221
222 $mainValue = $this->doGet( $key, self::READ_LATEST );
223 if ( !$this->doDelete( $key, $flags ) ) {
224 return false;
225 }
226
227 if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
228 // no segments to delete
229 return true;
230 }
231
232 $orderedKeys = array_map(
233 function ( $segmentHash ) use ( $key ) {
234 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
235 },
237 );
238
239 return $this->deleteMulti( $orderedKeys, $flags & ~self::WRITE_PRUNE_SEGMENTS );
240 }
241
250 abstract protected function doDelete( $key, $flags = 0 );
251
252 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
253 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
254
255 // Only when all segments (if any) are stored should the main key be changed
256 return $ok && $this->doAdd( $key, $entry, $exptime, $flags );
257 }
258
269 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
270
288 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
289 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
290 }
291
302 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
303 $attemptsLeft = $attempts;
304 do {
305 $token = self::PASS_BY_REF;
306 // Get the old value and CAS token from cache
307 $watchPoint = $this->watchErrors();
308 $currentValue = $this->resolveSegments(
309 $key,
310 $this->doGet( $key, $flags, $token )
311 );
312 if ( $this->getLastError( $watchPoint ) ) {
313 // Don't spam slow retries due to network problems (retry only on races)
314 $this->logger->warning(
315 __METHOD__ . ' failed due to read I/O error on get() for {key}.', [ 'key' => $key ]
316 );
317 $success = false;
318 break;
319 }
320
321 // Derive the new value from the old value
322 $value = $callback( $this, $key, $currentValue, $exptime );
323 $keyWasNonexistent = ( $currentValue === false );
324 $valueMatchesOldValue = ( $value === $currentValue );
325 // free RAM in case the value is large
326 unset( $currentValue );
327
328 $watchPoint = $this->watchErrors();
329 if ( $value === false || $exptime < 0 ) {
330 // do nothing
331 $success = true;
332 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
333 // recently set by another thread to the same value
334 $success = true;
335 } elseif ( $keyWasNonexistent ) {
336 // Try to create the key, failing if it gets created in the meantime
337 $success = $this->add( $key, $value, $exptime, $flags );
338 } else {
339 // Try to update the key, failing if it gets changed in the meantime
340 $success = $this->cas( $token, $key, $value, $exptime, $flags );
341 }
342 if ( $this->getLastError( $watchPoint ) ) {
343 // Don't spam slow retries due to network problems (retry only on races)
344 $this->logger->warning(
345 __METHOD__ . ' failed due to write I/O error for {key}.',
346 [ 'key' => $key ]
347 );
348 $success = false;
349 break;
350 }
351
352 } while ( !$success && --$attemptsLeft );
353
354 return $success;
355 }
356
368 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
369 if ( $casToken === null ) {
370 $this->logger->warning(
371 __METHOD__ . ' got empty CAS token for {key}.',
372 [ 'key' => $key ]
373 );
374
375 // caller may have meant to use add()?
376 return false;
377 }
378
379 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
380
381 // Only when all segments (if any) are stored should the main key be changed
382 return $ok && $this->doCas( $casToken, $key, $entry, $exptime, $flags );
383 }
384
396 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
397 // @TODO: the use of lock() assumes that all other relevant sets() use a lock
398 if ( !$this->lock( $key, 0 ) ) {
399 // non-blocking
400 return false;
401 }
402
403 $curCasToken = self::PASS_BY_REF;
404 $watchPoint = $this->watchErrors();
405 $exists = ( $this->doGet( $key, self::READ_LATEST, $curCasToken ) !== false );
406 if ( $this->getLastError( $watchPoint ) ) {
407 // Fail if the old CAS token could not be read
408 $success = false;
409 $this->logger->warning(
410 __METHOD__ . ' failed due to write I/O error for {key}.',
411 [ 'key' => $key ]
412 );
413 } elseif ( $exists && $this->tokensMatch( $casToken, $curCasToken ) ) {
414 $success = $this->doSet( $key, $value, $exptime, $flags );
415 } else {
416 // mismatched or failed
417 $success = false;
418 $this->logger->info(
419 __METHOD__ . ' failed due to race condition for {key}.',
420 [ 'key' => $key, 'key_exists' => $exists ]
421 );
422 }
423
424 $this->unlock( $key );
425
426 return $success;
427 }
428
435 final protected function tokensMatch( $value, $otherValue ) {
436 $type = gettype( $value );
437 // Ideally, tokens are counters, timestamps, hashes, or serialized PHP values.
438 // However, some classes might use the PHP values themselves.
439 if ( $type !== gettype( $otherValue ) ) {
440 return false;
441 }
442 // Serialize both tokens to strictly compare objects or arrays (which might objects
443 // nested inside). Note that this will not apply if integer/string CAS tokens are used.
444 if ( $type === 'array' || $type === 'object' ) {
445 return ( serialize( $value ) === serialize( $otherValue ) );
446 }
447
448 // For string/integer tokens, use a simple comparison
449 return ( $value === $otherValue );
450 }
451
470 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
471 return $this->doChangeTTL( $key, $exptime, $flags );
472 }
473
481 protected function doChangeTTL( $key, $exptime, $flags ) {
482 // @TODO: the use of lock() assumes that all other relevant sets() use a lock
483 if ( !$this->lock( $key, 0 ) ) {
484 return false;
485 }
486
487 $expiry = $this->getExpirationAsTimestamp( $exptime );
488 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
489
490 // Use doGet() to avoid having to trigger resolveSegments()
491 $blob = $this->doGet( $key, self::READ_LATEST );
492 if ( $blob ) {
493 if ( $delete ) {
494 $ok = $this->doDelete( $key, $flags );
495 } else {
496 $ok = $this->doSet( $key, $blob, $exptime, $flags );
497 }
498 } else {
499 $ok = false;
500 }
501
502 $this->unlock( $key );
503
504 return $ok;
505 }
506
507 public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 ) {
508 $step = (int)$step;
509 $init = is_int( $init ) ? $init : $step;
510
511 return $this->doIncrWithInit( $key, $exptime, $step, $init, $flags );
512 }
513
523 abstract protected function doIncrWithInit( $key, $exptime, $step, $init, $flags );
524
533 public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' ) {
534 $exptime = min( $exptime ?: INF, self::TTL_DAY );
535
536 $acquired = false;
537
538 if ( isset( $this->locks[$key] ) ) {
539 // Already locked; avoid deadlocks and allow lock reentry if specified
540 if ( $rclass != '' && $this->locks[$key][self::LOCK_RCLASS] === $rclass ) {
541 ++$this->locks[$key][self::LOCK_DEPTH];
542 $acquired = true;
543 }
544 } else {
545 // Not already locked; acquire a lock on the backend
546 $lockTsUnix = $this->doLock( $key, $timeout, $exptime );
547 if ( $lockTsUnix !== null ) {
548 $this->locks[$key] = [
549 self::LOCK_RCLASS => $rclass,
550 self::LOCK_DEPTH => 1,
551 self::LOCK_TIME => $lockTsUnix,
552 self::LOCK_EXPIRY => $lockTsUnix + $exptime
553 ];
554 $acquired = true;
555 }
556 }
557
558 return $acquired;
559 }
560
570 protected function doLock( $key, $timeout, $exptime ) {
571 $lockTsUnix = null;
572
573 $fname = __METHOD__;
574 $loop = new WaitConditionLoop(
575 function () use ( $key, $exptime, $fname, &$lockTsUnix ) {
576 $watchPoint = $this->watchErrors();
577 if ( $this->add( $this->makeLockKey( $key ), 1, $exptime ) ) {
578 $lockTsUnix = microtime( true );
579
580 return WaitConditionLoop::CONDITION_REACHED;
581 } elseif ( $this->getLastError( $watchPoint ) ) {
582 $this->logger->warning(
583 "$fname failed due to I/O error for {key}.",
584 [ 'key' => $key ]
585 );
586
587 return WaitConditionLoop::CONDITION_ABORTED;
588 }
589
590 return WaitConditionLoop::CONDITION_CONTINUE;
591 },
592 $timeout
593 );
594 $code = $loop->invoke();
595
596 if ( $code === $loop::CONDITION_TIMED_OUT ) {
597 $this->logger->warning(
598 "$fname failed due to timeout for {key}.",
599 [ 'key' => $key, 'timeout' => $timeout ]
600 );
601 }
602
603 return $lockTsUnix;
604 }
605
613 public function unlock( $key ) {
614 $released = false;
615
616 if ( isset( $this->locks[$key] ) ) {
617 if ( --$this->locks[$key][self::LOCK_DEPTH] > 0 ) {
618 $released = true;
619 } else {
620 $released = $this->doUnlock( $key );
621 unset( $this->locks[$key] );
622 if ( !$released ) {
623 $this->logger->warning(
624 __METHOD__ . ' failed to release lock for {key}.',
625 [ 'key' => $key ]
626 );
627 }
628 }
629 } else {
630 $this->logger->warning(
631 __METHOD__ . ' no lock to release for {key}.',
632 [ 'key' => $key ]
633 );
634 }
635
636 return $released;
637 }
638
646 protected function doUnlock( $key ) {
647 $released = false;
648
649 // Estimate the remaining TTL of the lock key
650 $curTTL = $this->locks[$key][self::LOCK_EXPIRY] - $this->getCurrentTime();
651
652 // Check the risk of race conditions for key deletion
653 if ( $this->getQoS( self::ATTR_DURABILITY ) <= self::QOS_DURABILITY_SCRIPT ) {
654 // Lock (and data) keys use memory specific to this request (e.g. HashBagOStuff)
655 $isSafe = true;
656 } else {
657 // It is unsafe to delete the lock key if there is a serious risk of the key already
658 // being claimed by another thread before the delete operation reaches the backend
659 $isSafe = ( $curTTL > $this->maxLockSendDelay );
660 }
661
662 if ( $isSafe ) {
663 $released = $this->doDelete( $this->makeLockKey( $key ) );
664 } else {
665 $this->logger->warning(
666 "Lock for {key} held too long ({age} sec).",
667 [ 'key' => $key, 'curTTL' => $curTTL ]
668 );
669 }
670
671 return $released;
672 }
673
679 protected function makeLockKey( $key ) {
680 return "$key:lock";
681 }
682
684 $timestamp,
685 callable $progress = null,
686 $limit = INF,
687 string $tag = null
688 ) {
689 return false;
690 }
691
700 public function getMulti( array $keys, $flags = 0 ) {
701 $foundByKey = $this->doGetMulti( $keys, $flags );
702
703 $res = [];
704 foreach ( $keys as $key ) {
705 // Resolve one blob at a time (avoids too much I/O at once)
706 if ( array_key_exists( $key, $foundByKey ) ) {
707 // A value should not appear in the key if a segment is missing
708 $value = $this->resolveSegments( $key, $foundByKey[$key] );
709 if ( $value !== false ) {
710 $res[$key] = $value;
711 }
712 }
713 }
714
715 return $res;
716 }
717
726 protected function doGetMulti( array $keys, $flags = 0 ) {
727 $res = [];
728 foreach ( $keys as $key ) {
729 $val = $this->doGet( $key, $flags );
730 if ( $val !== false ) {
731 $res[$key] = $val;
732 }
733 }
734
735 return $res;
736 }
737
750 public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) {
751 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
752 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_ALLOW_SEGMENTS' );
753 }
754
755 return $this->doSetMulti( $valueByKey, $exptime, $flags );
756 }
757
765 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
766 $res = true;
767 foreach ( $data as $key => $value ) {
768 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
769 }
770
771 return $res;
772 }
773
785 public function deleteMulti( array $keys, $flags = 0 ) {
786 if ( $this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
787 throw new InvalidArgumentException( __METHOD__ . ' got WRITE_PRUNE_SEGMENTS' );
788 }
789
790 return $this->doDeleteMulti( $keys, $flags );
791 }
792
799 protected function doDeleteMulti( array $keys, $flags = 0 ) {
800 $res = true;
801 foreach ( $keys as $key ) {
802 $res = $this->doDelete( $key, $flags ) && $res;
803 }
804
805 return $res;
806 }
807
819 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
820 return $this->doChangeTTLMulti( $keys, $exptime, $flags );
821 }
822
830 protected function doChangeTTLMulti( array $keys, $exptime, $flags = 0 ) {
831 $res = true;
832 foreach ( $keys as $key ) {
833 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
834 }
835
836 return $res;
837 }
838
847 final protected function resolveSegments( $key, $mainValue ) {
848 if ( SerializedValueContainer::isSegmented( $mainValue ) ) {
849 $orderedKeys = array_map(
850 function ( $segmentHash ) use ( $key ) {
851 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
852 },
854 );
855
856 $segmentsByKey = $this->doGetMulti( $orderedKeys );
857
858 $parts = [];
859 foreach ( $orderedKeys as $segmentKey ) {
860 if ( isset( $segmentsByKey[$segmentKey] ) ) {
861 $parts[] = $segmentsByKey[$segmentKey];
862 } else {
863 // missing segment
864 return false;
865 }
866 }
867
868 return $this->unserialize( implode( '', $parts ) );
869 }
870
871 return $mainValue;
872 }
873
887 private function useSegmentationWrapper( $value, $flags ) {
888 if (
889 $this->segmentationSize === INF ||
890 !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS )
891 ) {
892 return false;
893 }
894
895 if ( is_string( $value ) ) {
896 return ( strlen( $value ) >= $this->segmentationSize );
897 }
898
899 if ( is_array( $value ) ) {
900 // Expect that the contained value will be one of the first array entries
901 foreach ( array_slice( $value, 0, 4 ) as $v ) {
902 if ( is_string( $v ) && strlen( $v ) >= $this->segmentationSize ) {
903 return true;
904 }
905 }
906 }
907
908 // Avoid breaking functions for incrementing/decrementing integer key values
909 return false;
910 }
911
924 final protected function makeValueOrSegmentList( $key, $value, $exptime, $flags, &$ok ) {
925 $entry = $value;
926 $ok = true;
927
928 if ( $this->useSegmentationWrapper( $value, $flags ) ) {
929 $segmentSize = $this->segmentationSize;
930 $maxTotalSize = $this->segmentedValueMaxSize;
931 $serialized = $this->getSerialized( $value, $key );
932 $size = strlen( $serialized );
933 if ( $size > $maxTotalSize ) {
934 $this->logger->warning(
935 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
936 [ 'key' => $key ]
937 );
938 } else {
939 // Split the serialized value into chunks and store them at different keys
940 $chunksByKey = [];
941 $segmentHashes = [];
942 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
943 for ( $i = 0; $i < $count; ++$i ) {
944 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
945 $hash = sha1( $segment );
946 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
947 $chunksByKey[$chunkKey] = $segment;
948 $segmentHashes[] = $hash;
949 }
950 $flags &= ~self::WRITE_ALLOW_SEGMENTS;
951 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
952 $entry = SerializedValueContainer::newSegmented( $segmentHashes );
953 }
954 }
955
956 return $entry;
957 }
958
965 final protected function isRelativeExpiration( $exptime ) {
966 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
967 }
968
983 final protected function getExpirationAsTimestamp( $exptime ) {
984 if ( $exptime == self::TTL_INDEFINITE ) {
985 return $exptime;
986 }
987
988 return $this->isRelativeExpiration( $exptime )
989 ? intval( $this->getCurrentTime() + $exptime )
990 : $exptime;
991 }
992
1008 final protected function getExpirationAsTTL( $exptime ) {
1009 if ( $exptime == self::TTL_INDEFINITE ) {
1010 return $exptime;
1011 }
1012
1013 return $this->isRelativeExpiration( $exptime )
1014 ? $exptime
1015 : (int)max( $exptime - $this->getCurrentTime(), 1 );
1016 }
1017
1025 final protected function isInteger( $value ) {
1026 if ( is_int( $value ) ) {
1027 return true;
1028 } elseif ( !is_string( $value ) ) {
1029 return false;
1030 }
1031
1032 $integer = (int)$value;
1033
1034 return ( $value === (string)$integer );
1035 }
1036
1037 public function getQoS( $flag ) {
1038 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
1039 }
1040
1044 public function getSegmentationSize() {
1045 wfDeprecated( __METHOD__, '1.43' );
1046
1047 return $this->segmentationSize;
1048 }
1049
1053 public function getSegmentedValueMaxSize() {
1054 wfDeprecated( __METHOD__, '1.43' );
1055
1056 return $this->segmentedValueMaxSize;
1057 }
1058
1068 protected function getSerialized( $value, $key ) {
1069 $this->checkValueSerializability( $value, $key );
1070
1071 return $this->serialize( $value );
1072 }
1073
1094 private function checkValueSerializability( $value, $key ) {
1095 if ( is_array( $value ) ) {
1096 $this->checkIterableMapSerializability( $value, $key );
1097 } elseif ( is_object( $value ) ) {
1098 // Note that Closure instances count as objects
1099 if ( $value instanceof stdClass ) {
1100 $this->checkIterableMapSerializability( $value, $key );
1101 } elseif ( !( $value instanceof JsonSerializable ) ) {
1102 $this->logger->warning(
1103 "{class} value for '{cachekey}'; serialization is suspect.",
1104 [ 'cachekey' => $key, 'class' => get_class( $value ) ]
1105 );
1106 }
1107 }
1108 }
1109
1114 private function checkIterableMapSerializability( $value, $key ) {
1115 foreach ( $value as $index => $entry ) {
1116 if ( is_object( $entry ) ) {
1117 // Note that Closure instances count as objects
1118 if (
1119 !( $entry instanceof \stdClass ) &&
1120 !( $entry instanceof \JsonSerializable )
1121 ) {
1122 $this->logger->warning(
1123 "{class} value for '{cachekey}' at '$index'; serialization is suspect.",
1124 [ 'cachekey' => $key, 'class' => get_class( $entry ) ]
1125 );
1126
1127 return;
1128 }
1129 }
1130 }
1131 }
1132
1139 protected function serialize( $value ) {
1140 return is_int( $value ) ? $value : serialize( $value );
1141 }
1142
1149 protected function unserialize( $value ) {
1150 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1151 }
1152
1156 protected function debug( $text ) {
1157 $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] );
1158 }
1159
1165 private function determinekeyGroupForStats( $key ): string {
1166 // Key came directly from BagOStuff::makeKey() or BagOStuff::makeGlobalKey()
1167 // and thus has the format of "<scope>:<collection>[:<constant or variable>]..."
1168 $components = explode( ':', $key, 3 );
1169 // Handle legacy callers that fail to use the key building methods
1170 $keygroup = $components[1] ?? 'UNKNOWN';
1171
1172 return strtr( $keygroup, '.', '_' );
1173 }
1174
1182 protected function updateOpStats( string $op, array $keyInfo ) {
1183 $deltasByMetric = [];
1184
1185 foreach ( $keyInfo as $indexOrKey => $keyOrSizes ) {
1186 if ( is_array( $keyOrSizes ) ) {
1187 $key = $indexOrKey;
1188 [ $sPayloadSize, $rPayloadSize ] = $keyOrSizes;
1189 } else {
1190 $key = $keyOrSizes;
1191 $sPayloadSize = 0;
1192 $rPayloadSize = 0;
1193 }
1194
1195 // Metric prefix for the cache wrapper and key collection name
1196 $keygroup = $this->determinekeyGroupForStats( $key );
1197
1198 if ( $op === self::METRIC_OP_GET ) {
1199 // This operation was either a "hit" or "miss" for this key
1200 if ( $rPayloadSize === false ) {
1201 $statsdName = "objectcache.{$keygroup}.{$op}_miss_rate";
1202 $statsName = "bagostuff_miss_total";
1203 } else {
1204 $statsdName = "objectcache.{$keygroup}.{$op}_hit_rate";
1205 $statsName = "bagostuff_hit_total";
1206 }
1207 } else {
1208 // There is no concept of "hit" or "miss" for this operation
1209 $statsdName = "objectcache.{$keygroup}.{$op}_call_rate";
1210 $statsName = "bagostuff_call_total";
1211 }
1212 $deltasByMetric[$statsdName] = [
1213 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + 1,
1214 'metric' => $statsName,
1215 'keygroup' => $keygroup,
1216 'operation' => $op,
1217 ];
1218
1219 if ( $sPayloadSize > 0 ) {
1220 $statsdName = "objectcache.{$keygroup}.{$op}_bytes_sent";
1221 $statsName = "bagostuff_bytes_sent_total";
1222 $deltasByMetric[$statsdName] = [
1223 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + $sPayloadSize,
1224 'metric' => $statsName,
1225 'keygroup' => $keygroup,
1226 'operation' => $op,
1227 ];
1228 }
1229
1230 if ( $rPayloadSize > 0 ) {
1231 $statsdName = "objectcache.{$keygroup}.{$op}_bytes_read";
1232 $statsName = "bagostuff_bytes_read_total";
1233 $deltasByMetric[$statsdName] = [
1234 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + $rPayloadSize,
1235 'metric' => $statsName,
1236 'keygroup' => $keygroup,
1237 'operation' => $op,
1238 ];
1239 }
1240 }
1241
1242 foreach ( $deltasByMetric as $statsdName => $delta ) {
1243 $this->stats->getCounter( $delta['metric'] )
1244 ->setLabel( 'keygroup', $delta['keygroup'] )
1245 ->setLabel( 'operation', $delta['operation'] )
1246 ->copyToStatsdAt( $statsdName )
1247 ->incrementBy( $delta['delta'] );
1248 }
1249 }
1250}
1251
1253class_alias( MediumSpecificBagOStuff::class, 'MediumSpecificBagOStuff' );
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
array $params
The job parameters.
Helper class for segmenting large cache values without relying on serializing classes.
Class representing a cache/ephemeral data store.
Definition BagOStuff.php:88
makeGlobalKey( $keygroup,... $components)
Make a cache key from the given components, in the "global" keyspace.
Storage medium specific cache for storing items (e.g.
doGetMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
add( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
unlock( $key)
Release an advisory lock on a key string.
getSerialized( $value, $key)
Get the serialized form a value, logging a warning if it involves custom classes.
doGet( $key, $flags=0, &$casToken=null)
Get an item.
cas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.
changeTTLMulti(array $keys, $exptime, $flags=0)
Change the expiration of multiple keys that exist.
changeTTL( $key, $exptime=0, $flags=0)
Change the expiration on a key if it exists.
array< string, array > $locks
Map of (key => (class LOCK_* constant => value)
doDelete( $key, $flags=0)
Delete an item.
lock( $key, $timeout=6, $exptime=6, $rclass='')
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF, string $tag=null)
Delete all objects expiring before a certain date.
isInteger( $value)
Check if a value is an integer.
getExpirationAsTTL( $exptime)
Convert an optionally absolute expiry time to a relative time.
doIncrWithInit( $key, $exptime, $step, $init, $flags)
float $maxLockSendDelay
Seconds; maximum expected seconds for a lock ping to reach the backend.
int $segmentationSize
Bytes; chunk size of segmented cache values.
makeValueOrSegmentList( $key, $value, $exptime, $flags, &$ok)
Make the entry to store at a key (inline or segment list), storing any segments.
getMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
int $segmentedValueMaxSize
Bytes; maximum total size of a segmented cache value.
doCas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
setMulti(array $valueByKey, $exptime=0, $flags=0)
Batch insertion/replace.
mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags)
incrWithInit( $key, $exptime, $step=1, $init=null, $flags=0)
Increase the value of the given key (no TTL change) if it exists or create it otherwise.
resolveSegments( $key, $mainValue)
Get and reassemble the chunks of blob at the given key.
const PASS_BY_REF
Idiom for doGet() to return extra information by reference.
deleteMulti(array $keys, $flags=0)
Batch deletion.
getExpirationAsTimestamp( $exptime)
Convert an optionally relative timestamp to an absolute time.