MediaWiki master
MediumSpecificBagOStuff.php
Go to the documentation of this file.
1<?php
20namespace Wikimedia\ObjectCache;
21
22use InvalidArgumentException;
23use JsonSerializable;
24use stdClass;
25use Wikimedia\WaitConditionLoop;
26
36abstract class MediumSpecificBagOStuff extends BagOStuff {
38 protected $locks = [];
43
45 protected $maxLockSendDelay = 0.05;
46
48 private $duplicateKeyLookups = [];
50 private $reportDupes = false;
52 private $dupeTrackScheduled = false;
53
55 private const SEGMENT_COMPONENT = 'segment';
56
58 protected const PASS_BY_REF = -1;
59
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';
68
69 protected const LOCK_RCLASS = 0;
70 protected const LOCK_DEPTH = 1;
71 protected const LOCK_TIME = 2;
72 protected const LOCK_EXPIRY = 3;
73
92 public function __construct( array $params = [] ) {
93 parent::__construct( $params );
94
95 if ( !empty( $params['reportDupes'] ) && $this->asyncHandler ) {
96 $this->reportDupes = true;
97 }
98
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;
103 }
104
119 public function get( $key, $flags = 0 ) {
120 $this->trackDuplicateKeys( $key );
121
122 return $this->resolveSegments( $key, $this->doGet( $key, $flags ) );
123 }
124
130 private function trackDuplicateKeys( $key ) {
131 if ( !$this->reportDupes ) {
132 return;
133 }
134
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]++;
141
142 if ( $this->dupeTrackScheduled === false ) {
143 $this->dupeTrackScheduled = true;
144 // Schedule a callback that logs keys processed more than once by get().
145 ( $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, ]
152 );
153 }
154 } );
155 }
156 }
157 }
158
170 abstract protected function doGet( $key, $flags = 0, &$casToken = null );
171
172 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
173 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
174
175 // Only when all segments (if any) are stored should the main key be changed
176 return $ok && $this->doSet( $key, $entry, $exptime, $flags );
177 }
178
189 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
190
191 public function delete( $key, $flags = 0 ) {
192 if ( !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
193 return $this->doDelete( $key, $flags );
194 }
195
196 $mainValue = $this->doGet( $key, self::READ_LATEST );
197 if ( !$this->doDelete( $key, $flags ) ) {
198 return false;
199 }
200
201 if ( !SerializedValueContainer::isSegmented( $mainValue ) ) {
202 // no segments to delete
203 return true;
204 }
205
206 $orderedKeys = array_map(
207 function ( $segmentHash ) use ( $key ) {
208 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
209 },
211 );
212
213 return $this->deleteMulti( $orderedKeys, $flags & ~self::WRITE_ALLOW_SEGMENTS );
214 }
215
224 abstract protected function doDelete( $key, $flags = 0 );
225
226 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
227 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
228
229 // Only when all segments (if any) are stored should the main key be changed
230 return $ok && $this->doAdd( $key, $entry, $exptime, $flags );
231 }
232
243 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
244
262 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
263 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
264 }
265
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 )
285 );
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 ]
290 );
291 $success = false;
292 break;
293 }
294
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 );
301
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 );
315 }
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 ]
321 );
322 $success = false;
323 break;
324 }
325
326 } while ( !$success && --$attemptsLeft );
327
328 return $success;
329 }
330
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 ]
347 );
348
349 // caller may have meant to use add()?
350 return false;
351 }
352
353 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
354
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 );
357 }
358
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;
375 }
376
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 ]
386 );
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 ]
395 );
396 }
397
398 $this->unlock( $key );
399
400 return $success;
401 }
402
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;
415 }
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 ) );
420 }
421
422 // For string/integer tokens, use a simple comparison
423 return ( $value === $otherValue );
424 }
425
444 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
445 return $this->doChangeTTL( $key, $exptime, $flags );
446 }
447
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;
459 }
460
461 $expiry = $this->getExpirationAsTimestamp( $exptime );
462 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
463
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 );
471 }
472 } else {
473 $ok = false;
474 }
475
476 $this->unlock( $key );
477
478 return $ok;
479 }
480
481 public function incrWithInit( $key, $exptime, $step = 1, $init = null, $flags = 0 ) {
482 $step = (int)$step;
483 $init = is_int( $init ) ? $init : $step;
484
485 return $this->doIncrWithInit( $key, $exptime, $step, $init, $flags );
486 }
487
497 abstract protected function doIncrWithInit( $key, $exptime, $step, $init, $flags );
498
507 public function lock( $key, $timeout = 6, $exptime = 6, $rclass = '' ) {
508 $exptime = min( $exptime ?: INF, self::TTL_DAY );
509
510 $acquired = false;
511
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;
517 }
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
527 ];
528 $acquired = true;
529 }
530 }
531
532 return $acquired;
533 }
534
544 protected function doLock( $key, $timeout, $exptime ) {
545 $lockTsUnix = null;
546
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 );
553
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 ]
559 );
560
561 return WaitConditionLoop::CONDITION_ABORTED;
562 }
563
564 return WaitConditionLoop::CONDITION_CONTINUE;
565 },
566 $timeout
567 );
568 $code = $loop->invoke();
569
570 if ( $code === $loop::CONDITION_TIMED_OUT ) {
571 $this->logger->warning(
572 "$fname failed due to timeout for {key}.",
573 [ 'key' => $key, 'timeout' => $timeout ]
574 );
575 }
576
577 return $lockTsUnix;
578 }
579
587 public function unlock( $key ) {
588 $released = false;
589
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 ]
600 );
601 }
602 }
603 } else {
604 $this->logger->warning(
605 __METHOD__ . ' no lock to release for {key}.',
606 [ 'key' => $key ]
607 );
608 }
609
610 return $released;
611 }
612
620 protected function doUnlock( $key ) {
621 $released = false;
622
623 // Estimate the remaining TTL of the lock key
624 $curTTL = $this->locks[$key][self::LOCK_EXPIRY] - $this->getCurrentTime();
625
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 );
634 }
635
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 ]
642 );
643 }
644
645 return $released;
646 }
647
653 protected function makeLockKey( $key ) {
654 return "$key:lock";
655 }
656
658 $timestamp,
659 ?callable $progress = null,
660 $limit = INF,
661 ?string $tag = null
662 ) {
663 return false;
664 }
665
674 public function getMulti( array $keys, $flags = 0 ) {
675 $foundByKey = $this->doGetMulti( $keys, $flags );
676
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;
685 }
686 }
687 }
688
689 return $res;
690 }
691
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;
706 }
707 }
708
709 return $res;
710 }
711
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' );
727 }
728
729 return $this->doSetMulti( $valueByKey, $exptime, $flags );
730 }
731
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;
743 }
744
745 return $res;
746 }
747
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' );
751 }
752
753 return $this->doDeleteMulti( $keys, $flags );
754 }
755
762 protected function doDeleteMulti( array $keys, $flags = 0 ) {
763 $res = true;
764 foreach ( $keys as $key ) {
765 $res = $this->doDelete( $key, $flags ) && $res;
766 }
767
768 return $res;
769 }
770
782 public function changeTTLMulti( array $keys, $exptime, $flags = 0 ) {
783 return $this->doChangeTTLMulti( $keys, $exptime, $flags );
784 }
785
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;
797 }
798
799 return $res;
800 }
801
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 );
815 },
817 );
818
819 $segmentsByKey = $this->doGetMulti( $orderedKeys );
820
821 $parts = [];
822 foreach ( $orderedKeys as $segmentKey ) {
823 if ( isset( $segmentsByKey[$segmentKey] ) ) {
824 $parts[] = $segmentsByKey[$segmentKey];
825 } else {
826 // missing segment
827 return false;
828 }
829 }
830
831 return $this->unserialize( implode( '', $parts ) );
832 }
833
834 return $mainValue;
835 }
836
850 private function useSegmentationWrapper( $value, $flags ) {
851 if (
852 $this->segmentationSize === INF ||
853 !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS )
854 ) {
855 return false;
856 }
857
858 if ( is_string( $value ) ) {
859 return ( strlen( $value ) >= $this->segmentationSize );
860 }
861
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;
867 }
868 }
869 }
870
871 // Avoid breaking functions for incrementing/decrementing integer key values
872 return false;
873 }
874
887 final protected function makeValueOrSegmentList( $key, $value, $exptime, $flags, &$ok ) {
888 $entry = $value;
889 $ok = true;
890
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 ]
900 );
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;
912 }
913 $flags &= ~self::WRITE_ALLOW_SEGMENTS;
914 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
915 $entry = SerializedValueContainer::newSegmented( $segmentHashes );
916 }
917 }
918
919 return $entry;
920 }
921
928 final protected function isRelativeExpiration( $exptime ) {
929 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
930 }
931
946 final protected function getExpirationAsTimestamp( $exptime ) {
947 if ( $exptime == self::TTL_INDEFINITE ) {
948 return $exptime;
949 }
950
951 return $this->isRelativeExpiration( $exptime )
952 ? intval( $this->getCurrentTime() + $exptime )
953 : $exptime;
954 }
955
971 final protected function getExpirationAsTTL( $exptime ) {
972 if ( $exptime == self::TTL_INDEFINITE ) {
973 return $exptime;
974 }
975
976 return $this->isRelativeExpiration( $exptime )
977 ? $exptime
978 : (int)max( $exptime - $this->getCurrentTime(), 1 );
979 }
980
988 final protected function isInteger( $value ) {
989 if ( is_int( $value ) ) {
990 return true;
991 } elseif ( !is_string( $value ) ) {
992 return false;
993 }
994
995 $integer = (int)$value;
996
997 return ( $value === (string)$integer );
998 }
999
1000 public function getQoS( $flag ) {
1001 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
1002 }
1003
1007 public function getSegmentationSize() {
1008 wfDeprecated( __METHOD__, '1.43' );
1009
1010 return $this->segmentationSize;
1011 }
1012
1016 public function getSegmentedValueMaxSize() {
1017 wfDeprecated( __METHOD__, '1.43' );
1018
1019 return $this->segmentedValueMaxSize;
1020 }
1021
1031 protected function getSerialized( $value, $key ) {
1032 $this->checkValueSerializability( $value, $key );
1033
1034 return $this->serialize( $value );
1035 }
1036
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 ) ]
1068 );
1069 }
1070 }
1071 }
1072
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 )
1084 ) {
1085 $this->logger->warning(
1086 "{class} value for '{cachekey}' at '$index'; serialization is suspect.",
1087 [ 'cachekey' => $key, 'class' => get_class( $entry ) ]
1088 );
1089
1090 return;
1091 }
1092 }
1093 }
1094 }
1095
1102 protected function serialize( $value ) {
1103 return is_int( $value ) ? $value : serialize( $value );
1104 }
1105
1112 protected function unserialize( $value ) {
1113 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1114 }
1115
1119 protected function debug( $text ) {
1120 $this->logger->debug( "{class} debug: $text", [ 'class' => static::class ] );
1121 }
1122
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';
1134
1135 return strtr( $keygroup, '.', '_' );
1136 }
1137
1145 protected function updateOpStats( string $op, array $keyInfo ) {
1146 $deltasByMetric = [];
1147
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;
1156 }
1157
1158 // Metric prefix for the cache wrapper and key collection name
1159 $keygroup = $this->determinekeyGroupForStats( $key );
1160
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";
1169 }
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";
1174 }
1175 $deltasByMetric[$statsdName] = [
1176 'delta' => ( $deltasByMetric[$statsdName]['delta'] ?? 0 ) + 1,
1177 'metric' => $statsName,
1178 'keygroup' => $keygroup,
1179 'operation' => $op,
1180 ];
1181
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,
1190 ];
1191 }
1192
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,
1201 ];
1202 }
1203 }
1204
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'] );
1211 }
1212 }
1213}
1214
1216class_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.
Abstract class for any ephemeral data store.
Definition BagOStuff.php:88
makeGlobalKey( $keygroup,... $components)
Make a cache key from the given components, in the "global" keyspace.
Helper classs that implements most of BagOStuff for a backend.
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)
deleteObjectsExpiringBefore( $timestamp, ?callable $progress=null, $limit=INF, ?string $tag=null)
Delete all objects expiring before a certain date.
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)
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)
Delete a batch of items.
getExpirationAsTimestamp( $exptime)
Convert an optionally relative timestamp to an absolute time.