24use Wikimedia\WaitConditionLoop;
46 private $duplicateKeyLookups = [];
48 private $reportDupes =
false;
50 private $dupeTrackScheduled =
false;
53 private const SEGMENT_COMPONENT =
'segment';
91 if ( !empty(
$params[
'reportDupes'] ) && $this->asyncHandler ) {
92 $this->reportDupes =
true;
96 $this->segmentationSize =
$params[
'segmentationSize'] ?? 8_388_608;
98 $this->segmentedValueMaxSize =
$params[
'segmentedValueMaxSize'] ?? 67_108_864;
114 public function get( $key, $flags = 0 ) {
115 $this->trackDuplicateKeys( $key );
124 private function trackDuplicateKeys( $key ) {
125 if ( !$this->reportDupes ) {
129 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
132 $this->duplicateKeyLookups[$key] = 0;
134 $this->duplicateKeyLookups[$key] += 1;
136 if ( $this->dupeTrackScheduled ===
false ) {
137 $this->dupeTrackScheduled =
true;
139 call_user_func( $this->asyncHandler,
function () {
140 $dups = array_filter( $this->duplicateKeyLookups );
141 foreach ( $dups as $key => $count ) {
142 $this->logger->warning(
143 'Duplicate get(): "{key}" fetched {count} times',
145 [
'key' => $key,
'count' => $count + 1, ]
163 abstract protected function doGet( $key, $flags = 0, &$casToken =
null );
174 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
177 return $ok && $this->
doSet( $key, $entry, $exptime, $flags );
189 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
202 public function delete( $key, $flags = 0 ) {
203 if ( !$this->
fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
204 return $this->
doDelete( $key, $flags );
207 $mainValue = $this->
doGet( $key, self::READ_LATEST );
208 if ( !$this->
doDelete( $key, $flags ) ) {
217 $orderedKeys = array_map(
218 function ( $segmentHash ) use ( $key ) {
219 return $this->
makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
224 return $this->
deleteMulti( $orderedKeys, $flags & ~self::WRITE_PRUNE_SEGMENTS );
234 abstract protected function doDelete( $key, $flags = 0 );
236 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
237 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
239 return $ok && $this->doAdd( $key, $entry, $exptime, $flags );
251 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
269 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
270 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
282 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
283 $attemptsLeft = $attempts;
285 $token = self::PASS_BY_REF;
287 $watchPoint = $this->watchErrors();
288 $currentValue = $this->resolveSegments(
290 $this->doGet( $key, $flags, $token )
292 if ( $this->getLastError( $watchPoint ) ) {
294 $this->logger->warning(
295 __METHOD__ .
' failed due to read I/O error on get() for {key}.',
303 $value = $callback( $this, $key, $currentValue, $exptime );
304 $keyWasNonexistent = ( $currentValue === false );
305 $valueMatchesOldValue = ( $value === $currentValue );
307 unset( $currentValue );
309 $watchPoint = $this->watchErrors();
310 if ( $value ===
false || $exptime < 0 ) {
313 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
316 } elseif ( $keyWasNonexistent ) {
318 $success = $this->add( $key, $value, $exptime, $flags );
321 $success = $this->cas( $token, $key, $value, $exptime, $flags );
323 if ( $this->getLastError( $watchPoint ) ) {
325 $this->logger->warning(
326 __METHOD__ .
' failed due to write I/O error for {key}.',
333 }
while ( !
$success && --$attemptsLeft );
348 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
349 if ( $casToken ===
null ) {
350 $this->logger->warning(
351 __METHOD__ .
' got empty CAS token for {key}.',
359 $entry = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags, $ok );
361 return $ok && $this->doCas( $casToken, $key, $entry, $exptime, $flags );
374 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
376 if ( !$this->lock( $key, 0 ) ) {
381 $curCasToken = self::PASS_BY_REF;
382 $watchPoint = $this->watchErrors();
383 $exists = ( $this->doGet( $key, self::READ_LATEST, $curCasToken ) !== false );
384 if ( $this->getLastError( $watchPoint ) ) {
387 $this->logger->warning(
388 __METHOD__ .
' failed due to write I/O error for {key}.',
391 } elseif ( $exists && $this->tokensMatch( $casToken, $curCasToken ) ) {
392 $success = $this->doSet( $key, $value, $exptime, $flags );
397 __METHOD__ .
' failed due to race condition for {key}.',
398 [
'key' => $key,
'key_exists' => $exists ]
402 $this->unlock( $key );
413 $type = gettype( $value );
416 if ( $type !== gettype( $otherValue ) ) {
421 if ( $type ===
'array' || $type ===
'object' ) {
422 return ( serialize( $value ) === serialize( $otherValue ) );
425 return ( $value === $otherValue );
445 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
446 return $this->doChangeTTL( $key, $exptime, $flags );
457 if ( !$this->lock( $key, 0 ) ) {
461 $expiry = $this->getExpirationAsTimestamp( $exptime );
462 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
465 $blob = $this->doGet( $key, self::READ_LATEST );
468 $ok = $this->doDelete( $key, $flags );
470 $ok = $this->doSet( $key, $blob, $exptime, $flags );
476 $this->unlock( $key );
481 public function incrWithInit( $key, $exptime, $step = 1, $init =
null, $flags = 0 ) {
483 $init = is_int( $init ) ? $init : $step;
485 return $this->doIncrWithInit( $key, $exptime, $step, $init, $flags );
496 abstract protected function doIncrWithInit( $key, $exptime, $step, $init, $flags );
505 public function lock( $key, $timeout = 6, $exptime = 6, $rclass =
'' ) {
506 $exptime = min( $exptime ?: INF, self::TTL_DAY );
510 if ( isset( $this->locks[$key] ) ) {
512 if ( $rclass !=
'' && $this->locks[$key][self::LOCK_RCLASS] === $rclass ) {
513 ++$this->locks[$key][self::LOCK_DEPTH];
518 $lockTsUnix = $this->doLock( $key, $timeout, $exptime );
519 if ( $lockTsUnix !==
null ) {
520 $this->locks[$key] = [
521 self::LOCK_RCLASS => $rclass,
522 self::LOCK_DEPTH => 1,
523 self::LOCK_TIME => $lockTsUnix,
524 self::LOCK_EXPIRY => $lockTsUnix + $exptime
541 protected function doLock( $key, $timeout, $exptime ) {
545 $loop =
new WaitConditionLoop(
546 function () use ( $key, $exptime, $fname, &$lockTsUnix ) {
547 $watchPoint = $this->watchErrors();
548 if ( $this->add( $this->makeLockKey( $key ), 1, $exptime ) ) {
549 $lockTsUnix = microtime(
true );
551 return WaitConditionLoop::CONDITION_REACHED;
552 } elseif ( $this->getLastError( $watchPoint ) ) {
553 $this->logger->warning(
554 "$fname failed due to I/O error for {key}.",
558 return WaitConditionLoop::CONDITION_ABORTED;
561 return WaitConditionLoop::CONDITION_CONTINUE;
565 $code = $loop->invoke();
567 if ( $code === $loop::CONDITION_TIMED_OUT ) {
568 $this->logger->warning(
569 "$fname failed due to timeout for {key}.",
570 [
'key' => $key,
'timeout' => $timeout ]
586 if ( isset( $this->locks[$key] ) ) {
587 if ( --$this->locks[$key][self::LOCK_DEPTH] > 0 ) {
590 $released = $this->doUnlock( $key );
591 unset( $this->locks[$key] );
593 $this->logger->warning(
594 __METHOD__ .
' failed to release lock for {key}.',
600 $this->logger->warning(
601 __METHOD__ .
' no lock to release for {key}.',
619 $curTTL = $this->locks[$key][self::LOCK_EXPIRY] - $this->getCurrentTime();
622 if ( $this->getQoS( self::ATTR_DURABILITY ) <= self::QOS_DURABILITY_SCRIPT ) {
628 $isSafe = ( $curTTL > $this->maxLockSendDelay );
632 $released = $this->doDelete( $this->makeLockKey( $key ) );
634 $this->logger->warning(
635 "Lock for {key} held too long ({age} sec).",
636 [
'key' => $key,
'curTTL' => $curTTL ]
653 callable $progress =
null,
666 public function getMulti( array $keys, $flags = 0 ) {
667 $foundByKey = $this->doGetMulti( $keys, $flags );
670 foreach ( $keys as $key ) {
672 if ( array_key_exists( $key, $foundByKey ) ) {
674 $value = $this->resolveSegments( $key, $foundByKey[$key] );
675 if ( $value !==
false ) {
692 foreach ( $keys as $key ) {
693 $val = $this->doGet( $key, $flags );
694 if ( $val !==
false ) {
713 public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) {
714 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
715 throw new InvalidArgumentException( __METHOD__ .
' got WRITE_ALLOW_SEGMENTS' );
718 return $this->doSetMulti( $valueByKey, $exptime, $flags );
727 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
729 foreach ( $data as $key => $value ) {
730 $res = $this->doSet( $key, $value, $exptime, $flags ) && $res;
747 if ( $this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
748 throw new InvalidArgumentException( __METHOD__ .
' got WRITE_PRUNE_SEGMENTS' );
751 return $this->doDeleteMulti( $keys, $flags );
761 foreach ( $keys as $key ) {
762 $res = $this->doDelete( $key, $flags ) && $res;
778 return $this->doChangeTTLMulti( $keys, $exptime, $flags );
789 foreach ( $keys as $key ) {
790 $res = $this->doChangeTTL( $key, $exptime, $flags ) && $res;
805 $orderedKeys = array_map(
806 function ( $segmentHash ) use ( $key ) {
807 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
812 $segmentsByKey = $this->doGetMulti( $orderedKeys );
815 foreach ( $orderedKeys as $segmentKey ) {
816 if ( isset( $segmentsByKey[$segmentKey] ) ) {
817 $parts[] = $segmentsByKey[$segmentKey];
824 return $this->unserialize( implode(
'', $parts ) );
842 private function useSegmentationWrapper( $value, $flags ) {
844 $this->segmentationSize === INF ||
845 !$this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS )
850 if ( is_string( $value ) ) {
851 return ( strlen( $value ) >= $this->segmentationSize );
854 if ( is_array( $value ) ) {
856 foreach ( array_slice( $value, 0, 4 ) as $v ) {
857 if ( is_string( $v ) && strlen( $v ) >= $this->segmentationSize ) {
882 if ( $this->useSegmentationWrapper( $value, $flags ) ) {
883 $segmentSize = $this->segmentationSize;
884 $maxTotalSize = $this->segmentedValueMaxSize;
885 $serialized = $this->getSerialized( $value, $key );
886 $size = strlen( $serialized );
887 if ( $size > $maxTotalSize ) {
888 $this->logger->warning(
889 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
896 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
897 for ( $i = 0; $i < $count; ++$i ) {
898 $segment = substr( $serialized, $i * $segmentSize, $segmentSize );
899 $hash = sha1( $segment );
900 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
901 $chunksByKey[$chunkKey] = $segment;
902 $segmentHashes[] = $hash;
904 $flags &= ~self::WRITE_ALLOW_SEGMENTS;
905 $ok = $this->setMulti( $chunksByKey, $exptime, $flags );
919 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
936 if ( $exptime == self::TTL_INDEFINITE ) {
940 return $this->isRelativeExpiration( $exptime )
941 ? intval( $this->getCurrentTime() + $exptime )
960 if ( $exptime == self::TTL_INDEFINITE ) {
964 return $this->isRelativeExpiration( $exptime )
966 : (int)max( $exptime - $this->getCurrentTime(), 1 );
976 if ( is_int( $value ) ) {
978 } elseif ( !is_string( $value ) ) {
982 $integer = (int)$value;
984 return ( $value === (
string)$integer );
988 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
992 return $this->segmentationSize;
996 return $this->segmentedValueMaxSize;
1008 $this->checkValueSerializability( $value, $key );
1010 return $this->serialize( $value );
1033 private function checkValueSerializability( $value, $key ) {
1034 if ( is_array( $value ) ) {
1035 $this->checkIterableMapSerializability( $value, $key );
1036 } elseif ( is_object( $value ) ) {
1038 if ( $value instanceof stdClass ) {
1039 $this->checkIterableMapSerializability( $value, $key );
1040 } elseif ( !( $value instanceof JsonSerializable ) ) {
1041 $this->logger->warning(
1042 "{class} value for '{cachekey}'; serialization is suspect.",
1043 [
'cachekey' => $key,
'class' => get_class( $value ) ]
1053 private function checkIterableMapSerializability( $value, $key ) {
1054 foreach ( $value as $index => $entry ) {
1055 if ( is_object( $entry ) ) {
1058 !( $entry instanceof stdClass ) &&
1059 !( $entry instanceof JsonSerializable )
1061 $this->logger->warning(
1062 "{class} value for '{cachekey}' at '$index'; serialization is suspect.",
1063 [
'cachekey' => $key,
'class' => get_class( $entry ) ]
1078 return is_int( $value ) ? $value : serialize( $value );
1087 return $this->isInteger( $value ) ? (int)$value : unserialize( $value );
1094 $this->logger->debug(
"{class} debug: $text", [
'class' => static::class ] );
1101 private function determinekeyGroupForStats( $key ): string {
1104 $components = explode(
':', $key, 3 );
1106 $keygroup = $components[1] ??
'UNKNOWN';
1108 return strtr( $keygroup,
'.',
'_' );
1119 $deltasByMetric = [];
1121 foreach ( $keyInfo as $indexOrKey => $keyOrSizes ) {
1122 if ( is_array( $keyOrSizes ) ) {
1124 [ $sPayloadSize, $rPayloadSize ] = $keyOrSizes;
1132 $keygroup = $this->determinekeyGroupForStats( $key );
1134 if ( $op === self::METRIC_OP_GET ) {
1136 if ( $rPayloadSize ===
false ) {
1137 $statsdName =
"objectcache.{$keygroup}.{$op}_miss_rate";
1138 $statsName =
"bagostuff_miss_total";
1140 $statsdName =
"objectcache.{$keygroup}.{$op}_hit_rate";
1141 $statsName =
"bagostuff_hit_total";
1145 $statsdName =
"objectcache.{$keygroup}.{$op}_call_rate";
1146 $statsName =
"bagostuff_call_total";
1148 $deltasByMetric[$statsdName] = [
1149 'delta' => ( $deltasByMetric[$statsdName][
'delta'] ?? 0 ) + 1,
1150 'metric' => $statsName,
1151 'keygroup' => $keygroup,
1155 if ( $sPayloadSize > 0 ) {
1156 $statsdName =
"objectcache.{$keygroup}.{$op}_bytes_sent";
1157 $statsName =
"bagostuff_bytes_sent_total";
1158 $deltasByMetric[$statsdName] = [
1159 'delta' => ( $deltasByMetric[$statsdName][
'delta'] ?? 0 ) + $sPayloadSize,
1160 'metric' => $statsName,
1161 'keygroup' => $keygroup,
1166 if ( $rPayloadSize > 0 ) {
1167 $statsdName =
"objectcache.{$keygroup}.{$op}_bytes_read";
1168 $statsName =
"bagostuff_bytes_read_total";
1169 $deltasByMetric[$statsdName] = [
1170 'delta' => ( $deltasByMetric[$statsdName][
'delta'] ?? 0 ) + $rPayloadSize,
1171 'metric' => $statsName,
1172 'keygroup' => $keygroup,
1178 foreach ( $deltasByMetric as $statsdName => $delta ) {
1179 $this->stats->getCounter( $delta[
'metric'] )
1180 ->setLabel(
'keygroup', $delta[
'keygroup'] )
1181 ->setLabel(
'operation', $delta[
'operation'] )
1182 ->copyToStatsdAt( $statsdName )
1183 ->incrementBy( $delta[
'delta'] );
array $params
The job parameters.
Class representing a cache/ephemeral data store.
makeGlobalKey( $keygroup,... $components)
Make a cache key from the given components, in the "global" keyspace.
fieldHasFlags( $field, $flags)
Storage medium specific cache for storing items (e.g.
doSet( $key, $value, $exptime=0, $flags=0)
Set an item.
int $segmentationSize
Bytes; chunk size of segmented cache values.
cas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.
doDeleteMulti(array $keys, $flags=0)
const PASS_BY_REF
Idiom for doGet() to return extra information by reference.
setMulti(array $valueByKey, $exptime=0, $flags=0)
Batch insertion/replace.
const METRIC_OP_CHANGE_TTL
doChangeTTLMulti(array $keys, $exptime, $flags=0)
float $maxLockSendDelay
Seconds; maximum expected seconds for a lock ping to reach the backend.
getExpirationAsTimestamp( $exptime)
Convert an optionally relative timestamp to an absolute time.
getMulti(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.
deleteMulti(array $keys, $flags=0)
Batch deletion.
tokensMatch( $value, $otherValue)
getSerialized( $value, $key)
Get the serialized form a value, logging a warning if it involves custom classes.
doSetMulti(array $data, $exptime=0, $flags=0)
doChangeTTL( $key, $exptime, $flags)
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
unlock( $key)
Release an advisory lock on a key string.
doGetMulti(array $keys, $flags=0)
Get an associative array containing the item for each of the keys that have items.
doIncrWithInit( $key, $exptime, $step, $init, $flags)
updateOpStats(string $op, array $keyInfo)
array< string, array > $locks
Map of (key => (class LOCK_* constant => value)
doCas( $casToken, $key, $value, $exptime=0, $flags=0)
Set an item if the current CAS token matches the provided CAS token.
__construct(array $params=[])
doDelete( $key, $flags=0)
Delete an item.
doLock( $key, $timeout, $exptime)
mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags)
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
getSegmentedValueMaxSize()
getExpirationAsTTL( $exptime)
Convert an optionally absolute expiry time to a relative time.
isRelativeExpiration( $exptime)
resolveSegments( $key, $mainValue)
Get and reassemble the chunks of blob at the given key.
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.
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.
isInteger( $value)
Check if a value is an integer.
lock( $key, $timeout=6, $exptime=6, $rclass='')
makeValueOrSegmentList( $key, $value, $exptime, $flags, &$ok)
Make the entry to store at a key (inline or segment list), storing any segments.
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF, string $tag=null)
Delete all objects expiring before a certain date.
int $segmentedValueMaxSize
Bytes; maximum total size of a segmented cache value.
doGet( $key, $flags=0, &$casToken=null)
Get an item.
static newSegmented(array $segmentHashList)
static isSegmented( $value)