22use InvalidArgumentException;
26use Wikimedia\WaitConditionLoop;
49 private $duplicateKeyLookups = [];
51 private $reportDupes =
false;
53 private $dupeTrackScheduled =
false;
56 private const SEGMENT_COMPONENT =
'segment';
96 if ( !empty(
$params[
'reportDupes'] ) && $this->asyncHandler ) {
97 $this->reportDupes =
true;
101 $this->segmentationSize =
$params[
'segmentationSize'] ?? 8_388_608;
103 $this->segmentedValueMaxSize =
$params[
'segmentedValueMaxSize'] ?? 67_108_864;
120 public function get( $key, $flags = 0 ) {
121 $this->trackDuplicateKeys( $key );
131 private function trackDuplicateKeys( $key ) {
132 if ( !$this->reportDupes ) {
136 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
139 $this->duplicateKeyLookups[$key] = 0;
141 $this->duplicateKeyLookups[$key] += 1;
143 if ( $this->dupeTrackScheduled ===
false ) {
144 $this->dupeTrackScheduled =
true;
146 call_user_func( $this->asyncHandler,
function () {
147 $dups = array_filter( $this->duplicateKeyLookups );
148 foreach ( $dups as $key => $count ) {
149 $this->logger->warning(
150 'Duplicate get(): "{key}" fetched {count} times',
152 [
'key' => $key,
'count' => $count + 1, ]
171 abstract protected function doGet( $key, $flags = 0, &$casToken =
null );
173 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
177 return $ok && $this->
doSet( $key, $entry, $exptime, $flags );
190 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
192 public function delete( $key, $flags = 0 ) {
193 if ( !$this->
fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
194 return $this->
doDelete( $key, $flags );
197 $mainValue = $this->
doGet( $key, self::READ_LATEST );
198 if ( !$this->
doDelete( $key, $flags ) ) {
207 $orderedKeys = array_map(
208 function ( $segmentHash ) use ( $key ) {
209 return $this->
makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
214 return $this->
deleteMulti( $orderedKeys, $flags & ~self::WRITE_ALLOW_SEGMENTS );
225 abstract protected function doDelete( $key, $flags = 0 );
227 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
228 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
231 return $ok && $this->doAdd( $key, $entry, $exptime, $flags );
244 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
263 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
264 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
277 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
278 $attemptsLeft = $attempts;
280 $token = self::PASS_BY_REF;
282 $watchPoint = $this->watchErrors();
283 $currentValue = $this->resolveSegments(
285 $this->doGet( $key, $flags, $token )
287 if ( $this->getLastError( $watchPoint ) ) {
289 $this->logger->warning(
290 __METHOD__ .
' failed due to read I/O error on get() for {key}.', [
'key' => $key ]
297 $value = $callback( $this, $key, $currentValue, $exptime );
298 $keyWasNonexistent = ( $currentValue === false );
299 $valueMatchesOldValue = ( $value === $currentValue );
301 unset( $currentValue );
303 $watchPoint = $this->watchErrors();
304 if ( $value ===
false || $exptime < 0 ) {
307 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
310 } elseif ( $keyWasNonexistent ) {
312 $success = $this->add( $key, $value, $exptime, $flags );
315 $success = $this->cas( $token, $key, $value, $exptime, $flags );
317 if ( $this->getLastError( $watchPoint ) ) {
319 $this->logger->warning(
320 __METHOD__ .
' failed due to write I/O error for {key}.',
327 }
while ( !
$success && --$attemptsLeft );
343 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
344 if ( $casToken ===
null ) {
345 $this->logger->warning(
346 __METHOD__ .
' got empty CAS token for {key}.',
354 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
357 return $ok && $this->doCas( $casToken, $key, $entry, $exptime, $flags );
371 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
373 if ( !$this->lock( $key, 0 ) ) {
378 $curCasToken = self::PASS_BY_REF;
379 $watchPoint = $this->watchErrors();
380 $exists = ( $this->doGet( $key, self::READ_LATEST, $curCasToken ) !== false );
381 if ( $this->getLastError( $watchPoint ) ) {
384 $this->logger->warning(
385 __METHOD__ .
' failed due to write I/O error for {key}.',
388 } elseif ( $exists && $this->tokensMatch( $casToken, $curCasToken ) ) {
389 $success = $this->doSet( $key, $value, $exptime, $flags );
394 __METHOD__ .
' failed due to race condition for {key}.',
395 [
'key' => $key,
'key_exists' => $exists ]
399 $this->unlock( $key );
411 $type = gettype( $value );
414 if ( $type !== gettype( $otherValue ) ) {
419 if ( $type ===
'array' || $type ===
'object' ) {
420 return ( serialize( $value ) === serialize( $otherValue ) );
424 return ( $value === $otherValue );
445 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
446 return $this->doChangeTTL( $key, $exptime, $flags );
458 if ( !$this->lock( $key, 0 ) ) {
462 $expiry = $this->getExpirationAsTimestamp( $exptime );
463 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
466 $blob = $this->doGet( $key, self::READ_LATEST );
469 $ok = $this->doDelete( $key, $flags );
471 $ok = $this->doSet( $key, $blob, $exptime, $flags );
477 $this->unlock( $key );
482 public function incrWithInit( $key, $exptime, $step = 1, $init =
null, $flags = 0 ) {
484 $init = is_int( $init ) ? $init : $step;
486 return $this->doIncrWithInit( $key, $exptime, $step, $init, $flags );
498 abstract protected function doIncrWithInit( $key, $exptime, $step, $init, $flags );
508 public function lock( $key, $timeout = 6, $exptime = 6, $rclass =
'' ) {
509 $exptime = min( $exptime ?: INF, self::TTL_DAY );
513 if ( isset( $this->locks[$key] ) ) {
515 if ( $rclass !=
'' && $this->locks[$key][self::LOCK_RCLASS] === $rclass ) {
516 ++$this->locks[$key][self::LOCK_DEPTH];
521 $lockTsUnix = $this->doLock( $key, $timeout, $exptime );
522 if ( $lockTsUnix !==
null ) {
523 $this->locks[$key] = [
524 self::LOCK_RCLASS => $rclass,
525 self::LOCK_DEPTH => 1,
526 self::LOCK_TIME => $lockTsUnix,
527 self::LOCK_EXPIRY => $lockTsUnix + $exptime
545 protected function doLock( $key, $timeout, $exptime ) {
549 $loop =
new WaitConditionLoop(
550 function () use ( $key, $exptime, $fname, &$lockTsUnix ) {
551 $watchPoint = $this->watchErrors();
552 if ( $this->add( $this->makeLockKey( $key ), 1, $exptime ) ) {
553 $lockTsUnix = microtime(
true );
555 return WaitConditionLoop::CONDITION_REACHED;
556 } elseif ( $this->getLastError( $watchPoint ) ) {
557 $this->logger->warning(
558 "$fname failed due to I/O error for {key}.",
562 return WaitConditionLoop::CONDITION_ABORTED;
565 return WaitConditionLoop::CONDITION_CONTINUE;
569 $code = $loop->invoke();
571 if ( $code === $loop::CONDITION_TIMED_OUT ) {
572 $this->logger->warning(
573 "$fname failed due to timeout for {key}.",
574 [
'key' => $key,
'timeout' => $timeout ]
591 if ( isset( $this->locks[$key] ) ) {
592 if ( --$this->locks[$key][self::LOCK_DEPTH] > 0 ) {
595 $released = $this->doUnlock( $key );
596 unset( $this->locks[$key] );
598 $this->logger->warning(
599 __METHOD__ .
' failed to release lock for {key}.',
605 $this->logger->warning(
606 __METHOD__ .
' no lock to release for {key}.',
625 $curTTL = $this->locks[$key][self::LOCK_EXPIRY] - $this->getCurrentTime();
628 if ( $this->getQoS( self::ATTR_DURABILITY ) <= self::QOS_DURABILITY_SCRIPT ) {
634 $isSafe = ( $curTTL > $this->maxLockSendDelay );
638 $released = $this->doDelete( $this->makeLockKey( $key ) );
640 $this->logger->warning(
641 "Lock for {key} held too long ({age} sec).",
642 [
'key' => $key,
'curTTL' => $curTTL ]
660 ?callable $progress =
null,
675 public function getMulti( array $keys, $flags = 0 ) {
676 $foundByKey = $this->doGetMulti( $keys, $flags );
679 foreach ( $keys as $key ) {
681 if ( array_key_exists( $key, $foundByKey ) ) {
683 $value = $this->resolveSegments( $key, $foundByKey[$key] );
684 if ( $value !==
false ) {
703 foreach ( $keys as $key ) {
704 $val = $this->doGet( $key, $flags );
705 if ( $val !==
false ) {
725 public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) {
726 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
727 throw new InvalidArgumentException( __METHOD__ .
' got WRITE_ALLOW_SEGMENTS' );
730 return $this->doSetMulti( $valueByKey, $exptime, $flags );
740 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
742 foreach ( $data as $key => $value ) {
743 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
750 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
751 throw new InvalidArgumentException( __METHOD__ .
' got WRITE_ALLOW_SEGMENTS' );
754 return $this->doDeleteMulti( $keys, $flags );
765 foreach ( $keys as $key ) {
766 $res = $this->doDelete( $key, $flags ) && $res;
784 return $this->doChangeTTLMulti( $keys, $exptime, $flags );
796 foreach ( $keys as $key ) {
797 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
813 $orderedKeys = array_map(
814 function ( $segmentHash ) use ( $key ) {
815 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
820 $segmentsByKey = $this->doGetMulti( $orderedKeys );
823 foreach ( $orderedKeys as $segmentKey ) {
824 if ( isset( $segmentsByKey[$segmentKey] ) ) {
825 $parts[] = $segmentsByKey[$segmentKey];
832 return $this->unserialize( implode(
'', $parts ) );
851 private function useSegmentationWrapper( $value, $flags ) {
853 $this->segmentationSize === INF ||
854 !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS )
859 if ( is_string( $value ) ) {
860 return ( strlen( $value ) >= $this->segmentationSize );
863 if ( is_array( $value ) ) {
865 foreach ( array_slice( $value, 0, 4 ) as $v ) {
866 if ( is_string( $v ) && strlen( $v ) >= $this->segmentationSize ) {
892 if ( $this->useSegmentationWrapper( $value, $flags ) ) {
893 $segmentSize = $this->segmentationSize;
894 $maxTotalSize = $this->segmentedValueMaxSize;
895 $serialized = $this->getSerialized( $value, $key );
896 $size = strlen( $serialized );
897 if ( $size > $maxTotalSize ) {
898 $this->logger->warning(
899 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
906 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
907 for ( $i = 0; $i < $count; ++$i ) {
908 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
909 $hash = sha1( $segment );
910 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
911 $chunksByKey[$chunkKey] = $segment;
912 $segmentHashes[] = $hash;
914 $flags &= ~self::WRITE_ALLOW_SEGMENTS;
915 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
916 $entry = SerializedValueContainer::newSegmented( $segmentHashes );
930 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
948 if ( $exptime == self::TTL_INDEFINITE ) {
952 return $this->isRelativeExpiration( $exptime )
953 ? intval( $this->getCurrentTime() + $exptime )
973 if ( $exptime == self::TTL_INDEFINITE ) {
977 return $this->isRelativeExpiration( $exptime )
979 : (int)max( $exptime - $this->getCurrentTime(), 1 );
990 if ( is_int( $value ) ) {
992 } elseif ( !is_string( $value ) ) {
996 $integer = (int)$value;
998 return ( $value === (
string)$integer );
1002 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
1011 return $this->segmentationSize;
1020 return $this->segmentedValueMaxSize;
1033 $this->checkValueSerializability( $value, $key );
1035 return $this->serialize( $value );
1058 private function checkValueSerializability( $value, $key ) {
1059 if ( is_array( $value ) ) {
1060 $this->checkIterableMapSerializability( $value, $key );
1061 } elseif ( is_object( $value ) ) {
1063 if ( $value instanceof stdClass ) {
1064 $this->checkIterableMapSerializability( $value, $key );
1065 } elseif ( !( $value instanceof JsonSerializable ) ) {
1066 $this->logger->warning(
1067 "{class} value for '{cachekey}'; serialization is suspect.",
1068 [
'cachekey' => $key,
'class' => get_class( $value ) ]
1078 private function checkIterableMapSerializability( $value, $key ) {
1079 foreach ( $value as $index => $entry ) {
1080 if ( is_object( $entry ) ) {
1083 !( $entry instanceof \stdClass ) &&
1084 !( $entry instanceof \JsonSerializable )
1086 $this->logger->warning(
1087 "{class} value for '{cachekey}' at '$index'; serialization is suspect.",
1088 [
'cachekey' => $key,
'class' => get_class( $entry ) ]
1104 return is_int( $value ) ? $value : serialize( $value );
1114 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1121 $this->logger->debug(
"{class} debug: $text", [
'class' => static::class ] );
1129 private function determinekeyGroupForStats( $key ): string {
1132 $components = explode(
':', $key, 3 );
1134 $keygroup = $components[1] ??
'UNKNOWN';
1136 return strtr( $keygroup,
'.',
'_' );
1147 $deltasByMetric = [];
1149 foreach ( $keyInfo as $indexOrKey => $keyOrSizes ) {
1150 if ( is_array( $keyOrSizes ) ) {
1152 [ $sPayloadSize, $rPayloadSize ] = $keyOrSizes;
1160 $keygroup = $this->determinekeyGroupForStats( $key );
1162 if ( $op === self::METRIC_OP_GET ) {
1164 if ( $rPayloadSize ===
false ) {
1165 $statsdName =
"objectcache.{$keygroup}.{$op}_miss_rate";
1166 $statsName =
"bagostuff_miss_total";
1168 $statsdName =
"objectcache.{$keygroup}.{$op}_hit_rate";
1169 $statsName =
"bagostuff_hit_total";
1173 $statsdName =
"objectcache.{$keygroup}.{$op}_call_rate";
1174 $statsName =
"bagostuff_call_total";
1176 $deltasByMetric[$statsdName] = [
1177 'delta' => ( $deltasByMetric[$statsdName][
'delta'] ?? 0 ) + 1,
1178 'metric' => $statsName,
1179 'keygroup' => $keygroup,
1183 if ( $sPayloadSize > 0 ) {
1184 $statsdName =
"objectcache.{$keygroup}.{$op}_bytes_sent";
1185 $statsName =
"bagostuff_bytes_sent_total";
1186 $deltasByMetric[$statsdName] = [
1187 'delta' => ( $deltasByMetric[$statsdName][
'delta'] ?? 0 ) + $sPayloadSize,
1188 'metric' => $statsName,
1189 'keygroup' => $keygroup,
1194 if ( $rPayloadSize > 0 ) {
1195 $statsdName =
"objectcache.{$keygroup}.{$op}_bytes_read";
1196 $statsName =
"bagostuff_bytes_read_total";
1197 $deltasByMetric[$statsdName] = [
1198 'delta' => ( $deltasByMetric[$statsdName][
'delta'] ?? 0 ) + $rPayloadSize,
1199 'metric' => $statsName,
1200 'keygroup' => $keygroup,
1206 foreach ( $deltasByMetric as $statsdName => $delta ) {
1207 $this->stats->getCounter( $delta[
'metric'] )
1208 ->setLabel(
'keygroup', $delta[
'keygroup'] )
1209 ->setLabel(
'operation', $delta[
'operation'] )
1210 ->copyToStatsdAt( $statsdName )
1211 ->incrementBy( $delta[
'delta'] );
1217class_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.