24use Wikimedia\WaitConditionLoop;
62 private const SEGMENT_COMPONENT =
'segment';
84 parent::__construct( $params );
86 if ( isset( $params[
'keyspace'] ) ) {
87 $this->keyspace = $params[
'keyspace'];
90 if ( !empty( $params[
'reportDupes'] ) && is_callable( $this->asyncHandler ) ) {
91 $this->reportDupes =
true;
94 $this->syncTimeout = $params[
'syncTimeout'] ?? 3;
95 $this->segmentationSize = $params[
'segmentationSize'] ?? 8388608;
96 $this->segmentedValueMaxSize = $params[
'segmentedValueMaxSize'] ?? 67108864;
112 public function get( $key, $flags = 0 ) {
123 if ( !$this->reportDupes ) {
127 if ( !isset( $this->duplicateKeyLookups[$key] ) ) {
130 $this->duplicateKeyLookups[$key] = 0;
132 $this->duplicateKeyLookups[$key] += 1;
134 if ( $this->dupeTrackScheduled ===
false ) {
135 $this->dupeTrackScheduled =
true;
137 call_user_func( $this->asyncHandler,
function () {
138 $dups = array_filter( $this->duplicateKeyLookups );
139 foreach ( $dups as $key => $count ) {
140 $this->logger->warning(
141 'Duplicate get(): "{key}" fetched {count} times',
143 [
'key' => $key,
'count' => $count + 1, ]
157 abstract protected function doGet( $key, $flags = 0, &$casToken =
null );
168 public function set( $key, $value, $exptime = 0, $flags = 0 ) {
171 return $usable ? $this->
doSet( $key, $entry, $exptime, $flags ) :
false;
183 abstract protected function doSet( $key, $value, $exptime = 0, $flags = 0 );
196 public function delete( $key, $flags = 0 ) {
197 if ( !$this->
fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
198 return $this->
doDelete( $key, $flags );
201 $mainValue = $this->
doGet( $key, self::READ_LATEST );
202 if ( !$this->
doDelete( $key, $flags ) ) {
210 $orderedKeys = array_map(
211 function ( $segmentHash ) use ( $key ) {
212 return $this->
makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
217 return $this->
deleteMulti( $orderedKeys, $flags & ~self::WRITE_PRUNE_SEGMENTS );
227 abstract protected function doDelete( $key, $flags = 0 );
229 public function add( $key, $value, $exptime = 0, $flags = 0 ) {
230 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
232 return $usable ? $this->doAdd( $key, $entry, $exptime, $flags ) :
false;
244 abstract protected function doAdd( $key, $value, $exptime = 0, $flags = 0 );
262 public function merge( $key, callable $callback, $exptime = 0, $attempts = 10, $flags = 0 ) {
263 return $this->mergeViaCas( $key, $callback, $exptime, $attempts, $flags );
275 final protected function mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags ) {
276 $attemptsLeft = $attempts;
280 $this->clearLastError();
281 $currentValue = $this->resolveSegments(
283 $this->doGet( $key, $flags, $token )
285 if ( $this->getLastError() ) {
287 $this->logger->warning(
288 __METHOD__ .
' failed due to read I/O error on get() for {key}.',
296 $value = $callback( $this, $key, $currentValue, $exptime );
297 $keyWasNonexistant = ( $currentValue === false );
298 $valueMatchesOldValue = ( $value === $currentValue );
299 unset( $currentValue );
301 $this->clearLastError();
302 if ( $value ===
false || $exptime < 0 ) {
304 } elseif ( $valueMatchesOldValue && $attemptsLeft !== $attempts ) {
306 } elseif ( $keyWasNonexistant ) {
308 $success = $this->add( $key, $value, $exptime, $flags );
311 $success = $this->cas( $token, $key, $value, $exptime, $flags );
313 if ( $this->getLastError() ) {
315 $this->logger->warning(
316 __METHOD__ .
' failed due to write I/O error for {key}.',
323 }
while ( !
$success && --$attemptsLeft );
338 protected function cas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
339 if ( $casToken ===
null ) {
340 $this->logger->warning(
341 __METHOD__ .
' got empty CAS token for {key}.',
348 list( $entry, $usable ) = $this->makeValueOrSegmentList( $key, $value, $exptime, $flags );
350 return $usable ? $this->doCas( $casToken, $key, $entry, $exptime, $flags ) :
false;
363 protected function doCas( $casToken, $key, $value, $exptime = 0, $flags = 0 ) {
365 if ( !$this->lock( $key, 0 ) ) {
370 $this->clearLastError();
371 $this->doGet( $key, self::READ_LATEST, $curCasToken );
372 if ( is_object( $curCasToken ) ) {
374 throw new UnexpectedValueException(
"CAS token cannot be an object" );
376 if ( $this->getLastError() ) {
379 $this->logger->warning(
380 __METHOD__ .
' failed due to write I/O error for {key}.',
383 } elseif ( $casToken === $curCasToken ) {
384 $success = $this->doSet( $key, $value, $exptime, $flags );
388 __METHOD__ .
' failed due to race condition for {key}.',
393 $this->unlock( $key );
415 public function changeTTL( $key, $exptime = 0, $flags = 0 ) {
416 return $this->doChangeTTL( $key, $exptime, $flags );
426 if ( !$this->lock( $key, 0 ) ) {
430 $expiry = $this->getExpirationAsTimestamp( $exptime );
431 $delete = ( $expiry != self::TTL_INDEFINITE && $expiry < $this->getCurrentTime() );
434 $blob = $this->doGet( $key, self::READ_LATEST );
437 $ok = $this->doDelete( $key, $flags );
439 $ok = $this->doSet( $key,
$blob, $exptime, $flags );
445 $this->unlock( $key );
461 public function lock( $key, $timeout = 6, $expiry = 6, $rclass =
'' ) {
463 if ( isset( $this->locks[$key] ) ) {
464 if ( $rclass !=
'' && $this->locks[$key][
'class'] === $rclass ) {
465 ++$this->locks[$key][
'depth'];
473 $expiry = min( $expiry ?: INF, self::TTL_DAY );
474 $loop =
new WaitConditionLoop(
475 function () use ( $key, $expiry, $fname ) {
476 $this->clearLastError();
477 if ( $this->add(
"{$key}:lock", 1, $expiry ) ) {
478 return WaitConditionLoop::CONDITION_REACHED;
479 } elseif ( $this->getLastError() ) {
480 $this->logger->warning(
481 $fname .
' failed due to I/O error for {key}.',
485 return WaitConditionLoop::CONDITION_ABORTED;
488 return WaitConditionLoop::CONDITION_CONTINUE;
493 $code = $loop->invoke();
494 $locked = ( $code === $loop::CONDITION_REACHED );
496 $this->locks[$key] = [
'class' => $rclass,
'depth' => 1 ];
497 } elseif ( $code === $loop::CONDITION_TIMED_OUT ) {
498 $this->logger->warning(
499 "$fname failed due to timeout for {key}.",
500 [
'key' => $key,
'timeout' => $timeout ]
514 if ( !isset( $this->locks[$key] ) ) {
518 if ( --$this->locks[$key][
'depth'] <= 0 ) {
519 unset( $this->locks[$key] );
521 $ok = $this->doDelete(
"{$key}:lock" );
523 $this->logger->warning(
524 __METHOD__ .
' failed to release lock for {key}.',
547 callable $progress =
null,
560 $foundByKey = $this->doGetMulti(
$keys, $flags );
563 foreach (
$keys as $key ) {
565 if ( array_key_exists( $key, $foundByKey ) ) {
567 $value = $this->resolveSegments( $key, $foundByKey[$key] );
568 if ( $value !==
false ) {
585 foreach (
$keys as $key ) {
586 $val = $this->doGet( $key, $flags );
587 if ( $val !==
false ) {
606 public function setMulti( array $data, $exptime = 0, $flags = 0 ) {
607 if ( $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) ) {
608 throw new InvalidArgumentException( __METHOD__ .
' got WRITE_ALLOW_SEGMENTS' );
611 return $this->doSetMulti( $data, $exptime, $flags );
620 protected function doSetMulti( array $data, $exptime = 0, $flags = 0 ) {
622 foreach ( $data as $key => $value ) {
623 $res = $this->doSet( $key, $value, $exptime, $flags ) &&
$res;
640 if ( $this->fieldHasFlags( $flags, self::WRITE_PRUNE_SEGMENTS ) ) {
641 throw new InvalidArgumentException( __METHOD__ .
' got WRITE_PRUNE_SEGMENTS' );
644 return $this->doDeleteMulti(
$keys, $flags );
654 foreach (
$keys as $key ) {
655 $res = $this->doDelete( $key, $flags ) &&
$res;
673 foreach (
$keys as $key ) {
674 $res = $this->doChangeTTL( $key, $exptime, $flags ) &&
$res;
680 public function incrWithInit( $key, $exptime, $value = 1, $init =
null, $flags = 0 ) {
681 $init = is_int( $init ) ? $init : $value;
682 $this->clearLastError();
683 $newValue = $this->incr( $key, $value, $flags );
684 if ( $newValue ===
false && !$this->getLastError() ) {
686 $newValue = $this->add( $key, (
int)$init, $exptime, $flags ) ? $init :
false;
687 if ( $newValue ===
false && !$this->getLastError() ) {
689 $newValue = $this->incr( $key, $value, $flags );
709 $orderedKeys = array_map(
710 function ( $segmentHash ) use ( $key ) {
711 return $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $segmentHash );
716 $segmentsByKey = $this->doGetMulti( $orderedKeys );
719 foreach ( $orderedKeys as $segmentKey ) {
720 if ( isset( $segmentsByKey[$segmentKey] ) ) {
721 $parts[] = $segmentsByKey[$segmentKey];
727 return $this->
unserialize( implode(
'', $parts ) );
739 return $this->lastError;
747 $this->lastError = self::ERR_NONE;
756 $this->lastError = $err;
760 $this->busyCallbacks[] = $workCallback;
778 $this->fieldHasFlags( $flags, self::WRITE_ALLOW_SEGMENTS ) &&
780 is_finite( $this->segmentationSize )
782 $segmentSize = $this->segmentationSize;
783 $maxTotalSize = $this->segmentedValueMaxSize;
785 $serialized = $this->getSerialized( $value, $key );
787 if ( $size > $maxTotalSize ) {
788 $this->logger->warning(
789 "Value for {key} exceeds $maxTotalSize bytes; cannot segment.",
792 } elseif ( $size <= $segmentSize ) {
799 $count = intdiv( $size, $segmentSize ) + ( ( $size % $segmentSize ) ? 1 : 0 );
800 for ( $i = 0; $i < $count; ++$i ) {
801 $segment = substr(
$serialized, $i * $segmentSize, $segmentSize );
802 $hash = sha1( $segment );
803 $chunkKey = $this->makeGlobalKey( self::SEGMENT_COMPONENT, $key, $hash );
804 $chunksByKey[$chunkKey] = $segment;
805 $segmentHashes[] = $hash;
807 $flags &= ~self::WRITE_ALLOW_SEGMENTS;
808 $usable = $this->setMulti( $chunksByKey, $exptime, $flags );
813 return [ $entry, $usable ];
822 return ( $exptime !== self::TTL_INDEFINITE && $exptime < ( 10 * self::TTL_YEAR ) );
839 if ( $exptime == self::TTL_INDEFINITE ) {
843 return $this->isRelativeExpiration( $exptime )
844 ? intval( $this->getCurrentTime() + $exptime )
863 if ( $exptime == self::TTL_INDEFINITE ) {
867 return $this->isRelativeExpiration( $exptime )
869 : (int)max( $exptime - $this->getCurrentTime(), 1 );
879 if ( is_int( $value ) ) {
881 } elseif ( !is_string( $value ) ) {
885 $integer = (int)$value;
887 return ( $value === (
string)$integer );
892 foreach (
$args as $arg ) {
893 $key .=
':' . str_replace(
':',
'%3A', $arg );
895 return strtr( $key,
' ',
'_' );
907 return $this->makeKeyInternal(
'global', func_get_args() );
918 public function makeKey( $class, ...$components ) {
919 return $this->makeKeyInternal( $this->keyspace, func_get_args() );
928 return $this->attrMap[$flag] ?? self::QOS_UNKNOWN;
932 return $this->segmentationSize;
936 return $this->segmentedValueMaxSize;
940 $this->preparedValues = [];
943 foreach ( $valueByKey as $key => $value ) {
944 if ( $value ===
false ) {
952 $this->preparedValues[$key] = [ $value,
$serialized ];
970 if ( array_key_exists( $key, $this->preparedValues ) ) {
971 list( $prepValue, $prepSerialized ) = $this->preparedValues[$key];
977 if ( $prepValue === $value ) {
978 unset( $this->preparedValues[$key] );
980 return $prepSerialized;
1000 switch ( gettype( $value ) ) {
1003 return strlen( $value ) + 5;
1014 return $value ? 1 :
null;
1020 if ( $depth >= 5 && $loops >= 256 ) {
1028 foreach ( (array)$value as $k => $v ) {
1030 $size += is_string( $k ) ? ( strlen( $k ) + 5 ) : 23;
1031 $size += $this->guessSerialValueSize( $v, $depth + 1, $loops );
1046 return is_int( $value ) ? $value :
serialize( $value );
1055 return $this->isInteger( $value ) ? (int)$value :
unserialize( $value );
1062 if ( $this->debugMode ) {
1063 $this->logger->debug(
"{class} debug: $text", [
'class' => static::class ] );
unserialize( $serialized)
Class representing a cache/ephemeral data store.
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)
Check and set an item.
doDeleteMulti(array $keys, $flags=0)
guessSerialValueSize( $value, $depth=0, &$loops=0)
Estimate the size of a variable once serialized.
setMulti(array $data, $exptime=0, $flags=0)
Batch insertion/replace.
trackDuplicateKeys( $key)
Track the number of times that a given key has been used.
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.
makeKey( $class,... $components)
Make a cache key, scoped to this instance's keyspace.
lock( $key, $timeout=6, $expiry=6, $rclass='')
Acquire an advisory lock on a key string.
add( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
deleteMulti(array $keys, $flags=0)
Batch deletion.
addBusyCallback(callable $workCallback)
Let a callback be run to avoid wasting time on special blocking calls.
getSerialized( $value, $key)
Get the serialized form a value, using any applicable prepared value.
doSetMulti(array $data, $exptime=0, $flags=0)
doChangeTTL( $key, $exptime, $flags)
clearLastError()
Clear the "last error" registry.
merge( $key, callable $callback, $exptime=0, $attempts=10, $flags=0)
Merge changes into the existing cache value (possibly creating a new one)
array[] $locks
Lock tracking.
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.
makeGlobalKey( $class,... $components)
Make a global cache key.
doCas( $casToken, $key, $value, $exptime=0, $flags=0)
Check and set an item.
__construct(array $params=[])
doDelete( $key, $flags=0)
Delete an item.
mergeViaCas( $key, callable $callback, $exptime, $attempts, $flags)
getLastError()
Get the "last error" registered; clearLastError() should be called manually.
incrWithInit( $key, $exptime, $value=1, $init=null, $flags=0)
Increase the value of the given key (no TTL change) if it exists or create it otherwise.
doAdd( $key, $value, $exptime=0, $flags=0)
Insert an item if it does not already exist.
makeKeyInternal( $keyspace, $args)
Construct a cache key.
callable[] $busyCallbacks
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.
isInteger( $value)
Check if a value is an integer.
array $duplicateKeyLookups
setLastError( $err)
Set the "last error" registry.
deleteObjectsExpiringBefore( $timestamp, callable $progress=null, $limit=INF)
Delete all objects expiring before a certain date.
int $segmentedValueMaxSize
Bytes; maximum total size of a segmented cache value.
int $lastError
ERR_* class constant.
makeValueOrSegmentList( $key, $value, $exptime, $flags)
Determine the entry (inline or segment list) to store under a key to save the value.
array[] $preparedValues
Map of (key => (PHP variable value, serialized value))
setNewPreparedValues(array $valueByKey)
Prepare values for storage and get their serialized sizes, or, estimate those sizes.
doGet( $key, $flags=0, &$casToken=null)
static newSegmented(array $segmentHashList)
static isSegmented( $value)
static isUnified( $value)
static newUnified( $serialized)
foreach( $res as $row) $serialized