24 use Wikimedia\WaitConditionLoop;
60 private const SEGMENT_COMPONENT =
'segment';
63 protected const PASS_BY_REF = -1;
93 parent::__construct( $params );
95 if ( !empty( $params[
'reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
96 $this->reportDupes =
true;
99 $this->syncTimeout = $params[
'syncTimeout'] ?? 3;
100 $this->segmentationSize = $params[
'segmentationSize'] ?? 8388608;
101 $this->segmentedValueMaxSize = $params[
'segmentedValueMaxSize'] ?? 67108864;
117 public function get( $key, $flags = 0 ) {
128 if ( !$this->reportDupes ) {
132 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
135 $this->duplicateKeyLookups[$key] = 0;
137 $this->duplicateKeyLookups[$key] += 1;
139 if ( $this->dupeTrackScheduled ===
false ) {
140 $this->dupeTrackScheduled =
true;
142 call_user_func( $this->asyncHandler,
function () {
143 $dups = array_filter( $this->duplicateKeyLookups );
144 foreach ( $dups as $key => $count ) {
145 $this->logger->warning(
146 'Duplicate get(): "{key}" fetched {count} times',
148 [
'key' => $key,
'count' => $count + 1, ]
162 abstract protected function doGet( $key, $flags = 0, &$casToken =
null );
173 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
176 return $usable ? $this->
doSet( $key, $entry, $exptime, $flags ) :
false;
188 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
201 public function delete( $key, $flags = 0 ) {
202 if ( !$this->
fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
203 return $this->
doDelete( $key, $flags );
206 $mainValue = $this->
doGet( $key, self::READ_LATEST );
207 if ( !$this->
doDelete( $key, $flags ) ) {
215 $orderedKeys = array_map(
216 function ( $segmentHash ) use ( $key ) {
217 return $this->
makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
222 return $this->
deleteMulti( $orderedKeys, $flags & ~self::WRITE_PRUNE_SEGMENTS );
232 abstract protected function doDelete( $key, $flags = 0 );
234 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
235 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
237 return $usable ? $this->doAdd( $key, $entry, $exptime, $flags ) :
false;
249 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
267 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
268 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
280 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
281 $attemptsLeft = $attempts;
283 $token = self::PASS_BY_REF;
285 $this->clearLastError();
286 $currentValue = $this->resolveSegments(
288 $this->doGet( $key, $flags, $token )
290 if ( $this->getLastError() ) {
292 $this->logger->warning(
293 __METHOD__ .
' failed due to read I/O error on get() for {key}.',
301 $value = $callback( $this, $key, $currentValue, $exptime );
302 $keyWasNonexistant = ( $currentValue === false );
303 $valueMatchesOldValue = ( $value === $currentValue );
304 unset( $currentValue );
306 $this->clearLastError();
307 if ( $value ===
false || $exptime < 0 ) {
309 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
311 } elseif ( $keyWasNonexistant ) {
313 $success = $this->add( $key, $value, $exptime, $flags );
316 $success = $this->cas( $token, $key, $value, $exptime, $flags );
318 if ( $this->getLastError() ) {
320 $this->logger->warning(
321 __METHOD__ .
' failed due to write I/O error for {key}.',
328 }
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}.',
353 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
355 return $usable ? $this->doCas( $casToken, $key, $entry, $exptime, $flags ) :
false;
368 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
370 if ( !$this->lock( $key, 0 ) ) {
374 $curCasToken = self::PASS_BY_REF;
375 $this->clearLastError();
376 $this->doGet( $key, self::READ_LATEST, $curCasToken );
377 if ( is_object( $curCasToken ) ) {
379 throw new UnexpectedValueException(
"CAS token cannot be an object" );
381 if ( $this->getLastError() ) {
384 $this->logger->warning(
385 __METHOD__ .
' failed due to write I/O error for {key}.',
388 } elseif ( $casToken === $curCasToken ) {
389 $success = $this->doSet( $key, $value, $exptime, $flags );
393 __METHOD__ .
' failed due to race condition for {key}.',
398 $this->unlock( $key );
420 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
421 return $this->doChangeTTL( $key, $exptime, $flags );
432 if ( !$this->lock( $key, 0 ) ) {
436 $expiry = $this->getExpirationAsTimestamp( $exptime );
437 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
440 $blob = $this->doGet( $key, self::READ_LATEST );
443 $ok = $this->doDelete( $key, $flags );
445 $ok = $this->doSet( $key,
$blob, $exptime, $flags );
451 $this->unlock( $key );
467 public function lock( $key, $timeout = 6, $expiry = 6, $rclass =
'' ) {
469 if ( isset( $this->locks[$key] ) ) {
470 if ( $rclass !=
'' && $this->locks[$key][
'class'] === $rclass ) {
471 ++$this->locks[$key][
'depth'];
479 $expiry = min( $expiry ?: INF, self::TTL_DAY );
480 $loop =
new WaitConditionLoop(
481 function () use ( $key, $expiry, $fname ) {
482 $this->clearLastError();
483 if ( $this->add(
"{$key}:lock", 1, $expiry ) ) {
484 return WaitConditionLoop::CONDITION_REACHED;
485 } elseif ( $this->getLastError() ) {
486 $this->logger->warning(
487 $fname .
' failed due to I/O error for {key}.',
491 return WaitConditionLoop::CONDITION_ABORTED;
494 return WaitConditionLoop::CONDITION_CONTINUE;
499 $code = $loop->invoke();
500 $locked = ( $code === $loop::CONDITION_REACHED );
502 $this->locks[$key] = [
'class' => $rclass,
'depth' => 1 ];
503 } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
504 $this->logger->warning(
505 "$fname failed due to timeout for {key}.",
506 [
'key' => $key,
'timeout' => $timeout ]
520 if ( !isset( $this->locks[$key] ) ) {
524 if ( --$this->locks[$key][
'depth'] <= 0 ) {
525 unset( $this->locks[$key] );
527 $ok = $this->doDelete(
"{$key}:lock" );
529 $this->logger->warning(
530 __METHOD__ .
' failed to release lock for {key}.',
553 callable $progress =
null,
566 $foundByKey = $this->doGetMulti(
$keys, $flags );
569 foreach (
$keys as $key ) {
571 if ( array_key_exists( $key, $foundByKey ) ) {
573 $value = $this->resolveSegments( $key, $foundByKey[$key] );
574 if ( $value !==
false ) {
591 foreach (
$keys as $key ) {
592 $val = $this->doGet( $key, $flags );
593 if ( $val !==
false ) {
612 public function setMulti( array $valueByKey, $exptime = 0, $flags = 0 ) {
613 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
614 throw new InvalidArgumentException( __METHOD__ .
' got WRITE_ALLOW_SEGMENTS' );
617 return $this->doSetMulti( $valueByKey, $exptime, $flags );
626 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
628 foreach ( $data as $key => $value ) {
629 $res = $this->doSet( $key, $value, $exptime, $flags ) &&
$res;
646 if ( $this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
647 throw new InvalidArgumentException( __METHOD__ .
' got WRITE_PRUNE_SEGMENTS' );
650 return $this->doDeleteMulti(
$keys, $flags );
660 foreach (
$keys as $key ) {
661 $res = $this->doDelete( $key, $flags ) &&
$res;
677 return $this->doChangeTTLMulti(
$keys, $exptime, $flags );
688 foreach (
$keys as $key ) {
689 $res = $this->doChangeTTL( $key, $exptime, $flags ) &&
$res;
695 public function incrWithInit( $key, $exptime, $value = 1, $init =
null, $flags = 0 ) {
696 $init = is_int( $init ) ? $init : $value;
697 $this->clearLastError();
698 $newValue = $this->incr( $key, $value, $flags );
699 if ( $newValue ===
false && !$this->getLastError() ) {
701 $newValue = $this->add( $key, (
int)$init, $exptime, $flags ) ? $init :
false;
702 if ( $newValue ===
false && !$this->getLastError() ) {
704 $newValue = $this->incr( $key, $value, $flags );
724 $orderedKeys = array_map(
725 function ( $segmentHash ) use ( $key ) {
726 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
731 $segmentsByKey = $this->doGetMulti( $orderedKeys );
734 foreach ( $orderedKeys as $segmentKey ) {
735 if ( isset( $segmentsByKey[$segmentKey] ) ) {
736 $parts[] = $segmentsByKey[$segmentKey];
742 return $this->
unserialize( implode(
'', $parts ) );
754 return $this->lastError;
762 $this->lastError = self::ERR_NONE;
771 $this->lastError = $err;
775 $this->busyCallbacks[] = $workCallback;
793 $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) &&
795 is_finite( $this->segmentationSize )
797 $segmentSize = $this->segmentationSize;
798 $maxTotalSize = $this->segmentedValueMaxSize;
800 $serialized = $this->getSerialized( $value, $key );
802 if ( $size > $maxTotalSize ) {
803 $this->logger->warning(
804 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
807 } elseif ( $size <= $segmentSize ) {
814 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
815 for ( $i = 0; $i < $count; ++$i ) {
816 $segment = substr(
$serialized, $i * $segmentSize, $segmentSize );
817 $hash = sha1( $segment );
818 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
819 $chunksByKey[$chunkKey] = $segment;
820 $segmentHashes[] = $hash;
822 $flags &= ~self::WRITE_ALLOW_SEGMENTS;
823 $usable = $this->setMulti( $chunksByKey, $exptime, $flags );
828 return [ $entry, $usable ];
837 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
854 if ( $exptime == self::TTL_INDEFINITE ) {
858 return $this->isRelativeExpiration( $exptime )
859 ? intval( $this->getCurrentTime() + $exptime )
878 if ( $exptime == self::TTL_INDEFINITE ) {
882 return $this->isRelativeExpiration( $exptime )
884 : (int)max( $exptime - $this->getCurrentTime(), 1 );
894 if ( is_int( $value ) ) {
896 } elseif ( !is_string( $value ) ) {
900 $integer = (int)$value;
902 return ( $value === (
string)$integer );
906 return $this->makeKeyInternal( self::GLOBAL_KEYSPACE, func_get_args() );
909 public function makeKey( $collection, ...$components ) {
910 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
914 $components = $this->componentsFromGenericKey( $key );
915 if ( count( $components ) < 2 ) {
920 $keyspace = array_shift( $components );
922 return $this->makeKeyInternal( $keyspace, $components );
926 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
930 return $this->segmentationSize;
934 return $this->segmentedValueMaxSize;
938 $this->preparedValues = [];
941 foreach ( $valueByKey as $key => $value ) {
942 if ( $value ===
false ) {
950 $this->preparedValues[$key] = [ $value,
$serialized ];
968 if ( array_key_exists( $key, $this->preparedValues ) ) {
969 list( $prepValue, $prepSerialized ) = $this->preparedValues[$key];
975 if ( $prepValue === $value ) {
976 unset( $this->preparedValues[$key] );
978 return $prepSerialized;
998 switch ( gettype( $value ) ) {
1001 return strlen( $value ) + 5;
1012 return $value ? 1 :
null;
1018 if ( $depth >= 5 && $loops >= 256 ) {
1026 foreach ( (array)$value as $k => $v ) {
1028 $size += is_string( $k ) ? ( strlen( $k ) + 5 ) : 23;
1029 $size += $this->guessSerialValueSize( $v, $depth + 1, $loops );
1044 return is_int( $value ) ? $value :
serialize( $value );
1053 return $this->isInteger( $value ) ? (int)$value :
unserialize( $value );
1060 $this->logger->debug(
"{class} debug: $text", [
'class' => static::class ] );
1071 $deltasByMetric = [];
1073 foreach ( $keyInfo as $indexOrKey => $keyOrSizes ) {
1074 if ( is_array( $keyOrSizes ) ) {
1076 list( $sPayloadSize, $rPayloadSize ) = $keyOrSizes;
1079 $sPayloadSize =
null;
1080 $rPayloadSize =
null;
1084 $prefix = $this->determineKeyPrefixForStats( $key );
1086 if ( $op === self::METRIC_OP_GET ) {
1088 $name =
"{$prefix}.{$op}_" . ( $rPayloadSize ===
false ?
'miss_rate' :
'hit_rate' );
1091 $name =
"{$prefix}.{$op}_call_rate";
1093 $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + 1;
1095 if ( $sPayloadSize > 0 ) {
1096 $name =
"{$prefix}.{$op}_bytes_sent";
1097 $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + $sPayloadSize;
1100 if ( $rPayloadSize > 0 ) {
1101 $name =
"{$prefix}.{$op}_bytes_read";
1102 $deltasByMetric[$name] = ( $deltasByMetric[$name] ?? 0 ) + $rPayloadSize;
1106 foreach ( $deltasByMetric as $name => $delta ) {
1107 $this->stats->updateCount( $name, $delta );