199 private $callbackDepth = 0;
201 private $warmupCache = [];
203 private $warmupKeyMisses = 0;
206 private $wallClockOverride;
209 private const MAX_COMMIT_DELAY = 3;
211 private const MAX_READ_LAG = 7;
213 public const HOLDOFF_TTL = self::MAX_COMMIT_DELAY + self::MAX_READ_LAG + 1;
216 private const LOW_TTL = 60;
221 private const HOT_TTR = 900;
223 private const AGE_NEW = 60;
226 private const TSE_NONE = -1;
236 public const MIN_TIMESTAMP_NONE = 0.0;
239 private const PC_PRIMARY =
'primary:1000';
245 private const SCHEME_HASH_TAG = 1;
247 private const SCHEME_HASH_STOP = 2;
250 private const CHECK_KEY_TTL = self::TTL_YEAR;
252 private const INTERIM_KEY_TTL = 2;
255 private const LOCK_TTL = 10;
257 private const RAMPUP_TTL = 30;
260 private const TINY_NEGATIVE = -0.000001;
262 private const TINY_POSITIVE = 0.000001;
265 private const RECENT_SET_LOW_MS = 50;
267 private const RECENT_SET_HIGH_MS = 100;
270 private const GENERATION_HIGH_SEC = 0.2;
273 private const PURGE_TIME = 0;
275 private const PURGE_HOLDOFF = 1;
278 private const VERSION = 1;
294 private const RES_VALUE = 0;
296 private const RES_VERSION = 1;
298 private const RES_AS_OF = 2;
300 private const RES_TTL = 3;
302 private const RES_TOMB_AS_OF = 4;
304 private const RES_CHECK_AS_OF = 5;
306 private const RES_TOUCH_AS_OF = 6;
308 private const RES_CUR_TTL = 7;
311 private const FLD_FORMAT_VERSION = 0;
313 private const FLD_VALUE = 1;
315 private const FLD_TTL = 2;
317 private const FLD_TIME = 3;
319 private const FLD_FLAGS = 4;
321 private const FLD_VALUE_VERSION = 5;
322 private const FLD_GENERATION_TIME = 6;
325 private const TYPE_VALUE =
'v';
327 private const TYPE_TIMESTAMP =
't';
329 private const TYPE_MUTEX =
'm';
331 private const TYPE_INTERIM =
'i';
334 private const PURGE_VAL_PREFIX =
'PURGED';
364 $this->cache =
$params[
'cache'];
365 $this->broadcastRoute =
$params[
'broadcastRoutingPrefix'] ??
null;
366 $this->epoch =
$params[
'epoch'] ?? 0;
367 $this->secret =
$params[
'secret'] ?? (string)$this->epoch;
368 if ( (
$params[
'coalesceScheme'] ??
'' ) ===
'hash_tag' ) {
372 $this->coalesceScheme = self::SCHEME_HASH_TAG;
375 $this->coalesceScheme = self::SCHEME_HASH_STOP;
378 $this->
setLogger( $params[
'logger'] ??
new NullLogger() );
383 'Use of StatsdDataFactory is deprecated in 1.43. Use StatsFactory instead.'
387 $this->stats =
$params[
'stats'] ?? StatsFactory::newNull();
389 $this->asyncHandler =
$params[
'asyncHandler'] ??
null;
390 $this->missLog = array_fill( 0, 10, [
'', 0.0 ] );
461 final public function get( $key, &$curTTL =
null, array $checkKeys = [], &$info = [] ) {
467 $res = $this->
fetchKeys( [ $key ], $checkKeys, $now )[$key];
469 $curTTL = $res[self::RES_CUR_TTL];
471 ? $res[self::RES_AS_OF]
473 self::KEY_VERSION => $res[self::RES_VERSION],
474 self::KEY_AS_OF => $res[self::RES_AS_OF],
475 self::KEY_TTL => $res[self::RES_TTL],
476 self::KEY_CUR_TTL => $res[self::RES_CUR_TTL],
477 self::KEY_TOMB_AS_OF => $res[self::RES_TOMB_AS_OF],
478 self::KEY_CHECK_AS_OF => $res[self::RES_CHECK_AS_OF]
481 if ( $curTTL ===
null || $curTTL <= 0 ) {
483 unset( $this->missLog[array_key_first( $this->missLog )] );
487 return $res[self::RES_VALUE];
517 array $checkKeys = [],
529 $resByKey = $this->
fetchKeys( $keys, $checkKeys, $now );
530 foreach ( $resByKey as $key => $res ) {
531 if ( $res[self::RES_VALUE] !==
false ) {
532 $valuesByKey[$key] = $res[self::RES_VALUE];
535 if ( $res[self::RES_CUR_TTL] !==
null ) {
536 $curTTLs[$key] = $res[self::RES_CUR_TTL];
538 $info[$key] = $legacyInfo
539 ? $res[self::RES_AS_OF]
541 self::KEY_VERSION => $res[self::RES_VERSION],
542 self::KEY_AS_OF => $res[self::RES_AS_OF],
543 self::KEY_TTL => $res[self::RES_TTL],
544 self::KEY_CUR_TTL => $res[self::RES_CUR_TTL],
545 self::KEY_TOMB_AS_OF => $res[self::RES_TOMB_AS_OF],
546 self::KEY_CHECK_AS_OF => $res[self::RES_CHECK_AS_OF]
568 protected function fetchKeys( array $keys, array $checkKeys,
float $now, $touchedCb =
null ) {
574 $valueSisterKeys = [];
576 $checkSisterKeysForAll = [];
578 $checkSisterKeysByKey = [];
580 foreach ( $keys as $key ) {
581 $sisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE );
582 $allSisterKeys[] = $sisterKey;
583 $valueSisterKeys[] = $sisterKey;
586 foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) {
588 if ( is_int( $i ) ) {
590 $sisterKey = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP );
591 $allSisterKeys[] = $sisterKey;
592 $checkSisterKeysForAll[] = $sisterKey;
595 foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) {
596 $sisterKey = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP );
597 $allSisterKeys[] = $sisterKey;
598 $checkSisterKeysByKey[$i][] = $sisterKey;
603 if ( $this->warmupCache ) {
605 $wrappedBySisterKey = $this->warmupCache;
606 $sisterKeysMissing = array_diff( $allSisterKeys, array_keys( $wrappedBySisterKey ) );
607 if ( $sisterKeysMissing ) {
608 $this->warmupKeyMisses += count( $sisterKeysMissing );
609 $wrappedBySisterKey += $this->cache->getMulti( $sisterKeysMissing );
613 $wrappedBySisterKey = $this->cache->getMulti( $allSisterKeys );
617 $ckPurgesForAll = $this->processCheckKeys(
618 $checkSisterKeysForAll,
624 foreach ( $checkSisterKeysByKey as $keyWithCheckKeys => $checkKeysForKey ) {
625 $ckPurgesByKey[$keyWithCheckKeys] = $this->processCheckKeys(
634 array_map(
null, $valueSisterKeys, $keys )
635 as [ $valueSisterKey, $key ]
637 if ( array_key_exists( $valueSisterKey, $wrappedBySisterKey ) ) {
639 $wrapped = $wrappedBySisterKey[$valueSisterKey];
645 $res = $this->unwrap( $wrapped, $now );
646 $value = $res[self::RES_VALUE];
648 foreach ( array_merge( $ckPurgesForAll, $ckPurgesByKey[$key] ?? [] ) as $ckPurge ) {
649 $res[self::RES_CHECK_AS_OF] = max(
650 $ckPurge[self::PURGE_TIME],
651 $res[self::RES_CHECK_AS_OF]
654 $holdoffDeadline = $ckPurge[self::PURGE_TIME] + $ckPurge[self::PURGE_HOLDOFF];
656 if ( $value !==
false && $holdoffDeadline >= $res[self::RES_AS_OF] ) {
658 $ago = min( $ckPurge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
660 $res[self::RES_CUR_TTL] = min( $res[self::RES_CUR_TTL], $ago );
664 if ( $touchedCb !==
null && $value !==
false ) {
665 $touched = $touchedCb( $value );
666 if ( $touched !==
null && $touched >= $res[self::RES_AS_OF] ) {
667 $res[self::RES_CUR_TTL] = min(
668 $res[self::RES_CUR_TTL],
669 $res[self::RES_AS_OF] - $touched,
677 $res[self::RES_TOUCH_AS_OF] = max( $res[self::RES_TOUCH_AS_OF], $touched );
679 $resByKey[$key] = $res;
691 private function processCheckKeys(
692 array $checkSisterKeys,
693 array $wrappedBySisterKey,
698 foreach ( $checkSisterKeys as $timeKey ) {
699 $purge = isset( $wrappedBySisterKey[$timeKey] )
700 ? $this->parsePurgeValue( $wrappedBySisterKey[$timeKey] )
703 if ( $purge ===
null ) {
705 $wrapped = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL_NONE, $purge );
710 $this->cache::WRITE_BACKGROUND
803 final public function set( $key, $value, $ttl = self::TTL_INDEFINITE, array $opts = [] ) {
804 $keygroup = $this->determineKeyGroupForStats( $key );
806 $ok = $this->setMainValue(
810 $opts[
'version'] ??
null,
811 $opts[
'walltime'] ??
null,
813 $opts[
'since'] ??
null,
814 $opts[
'pending'] ??
false,
815 $opts[
'lockTSE'] ?? self::TSE_NONE,
816 $opts[
'staleTTL'] ?? self::STALE_TTL_NONE,
817 $opts[
'segmentable'] ??
false,
818 $opts[
'creating'] ??
false
821 $this->stats->getCounter(
'wanobjectcache_set_total' )
822 ->setLabel(
'keygroup', $keygroup )
823 ->setLabel(
'result', ( $ok ?
'ok' :
'error' ) )
824 ->copyToStatsdAt(
"wanobjectcache.$keygroup.set." . ( $ok ?
'ok' :
'error' ) )
845 private function setMainValue(
853 bool $dataPendingCommit,
866 $walltime ??= $this->timeSinceLoggedMiss( $key, $now );
867 $dataSnapshotLag = ( $dataReadSince !== null ) ? max( 0, $now - $dataReadSince ) : 0;
868 $dataCombinedLag = $dataReplicaLag + $dataSnapshotLag;
875 if ( $dataPendingCommit ) {
877 $mitigated =
'pending writes';
879 $mitigationTTL = self::TTL_UNCACHEABLE;
880 } elseif ( $dataSnapshotLag > self::MAX_READ_LAG ) {
882 $pregenSnapshotLag = ( $walltime !== null ) ? ( $dataSnapshotLag - $walltime ) : 0;
883 if ( ( $pregenSnapshotLag + self::GENERATION_HIGH_SEC ) > self::MAX_READ_LAG ) {
885 $mitigated =
'snapshot lag (late generation)';
887 $mitigationTTL = self::TTL_UNCACHEABLE;
890 $mitigated =
'snapshot lag (high generation time)';
894 } elseif ( $dataReplicaLag ===
false || $dataReplicaLag > self::MAX_READ_LAG ) {
896 $mitigated =
'replication lag';
899 } elseif ( $dataCombinedLag > self::MAX_READ_LAG ) {
900 $pregenCombinedLag = ( $walltime !== null ) ? ( $dataCombinedLag - $walltime ) : 0;
902 if ( ( $pregenCombinedLag + self::GENERATION_HIGH_SEC ) > self::MAX_READ_LAG ) {
904 $mitigated =
'read lag (late generation)';
906 $mitigationTTL = self::TTL_UNCACHEABLE;
909 $mitigated =
'read lag (high generation time)';
917 $mitigationTTL =
null;
920 if ( $mitigationTTL === self::TTL_UNCACHEABLE ) {
921 $this->logger->warning(
922 "Rejected set() for {cachekey} due to $mitigated.",
925 'lag' => $dataReplicaLag,
926 'age' => $dataSnapshotLag,
927 'walltime' => $walltime
938 if ( $mitigationTTL !==
null ) {
940 if ( $lockTSE >= 0 ) {
942 $logicalTTL = min( $ttl ?: INF, $mitigationTTL );
945 $ttl = min( $ttl ?: INF, $mitigationTTL );
948 $this->logger->warning(
949 "Lowered set() TTL for {cachekey} due to $mitigated.",
952 'lag' => $dataReplicaLag,
953 'age' => $dataSnapshotLag,
954 'walltime' => $walltime
960 $wrapped = $this->wrap( $value, $logicalTTL ?: $ttl, $version, $now );
961 $storeTTL = $ttl + $staleTTL;
963 $flags = $this->cache::WRITE_BACKGROUND;
964 if ( $segmentable ) {
965 $flags |= $this->cache::WRITE_ALLOW_SEGMENTS;
969 $ok = $this->cache->add(
970 $this->makeSisterKey( $key, self::TYPE_VALUE ),
976 $ok = $this->cache->merge(
977 $this->makeSisterKey( $key, self::TYPE_VALUE ),
978 static function (
$cache, $key, $cWrapped ) use ( $wrapped ) {
980 return ( is_string( $cWrapped ) ) ?
false : $wrapped;
983 $this->cache::MAX_CONFLICTS_ONE,
1057 $valueSisterKey = $this->makeSisterKey( $key, self::TYPE_VALUE );
1073 $purge = $this->makeTombstonePurgeValue( $now );
1077 $keygroup = $this->determineKeyGroupForStats( $key );
1079 $this->stats->getCounter(
'wanobjectcache_delete_total' )
1080 ->setLabel(
'keygroup', $keygroup )
1081 ->setLabel(
'result', ( $ok ?
'ok' :
'error' ) )
1082 ->copyToStatsdAt(
"wanobjectcache.$keygroup.delete." . ( $ok ?
'ok' :
'error' ) )
1173 $checkSisterKeysByKey = [];
1174 foreach ( $keys as $key ) {
1175 $checkSisterKeysByKey[$key] = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1178 $wrappedBySisterKey = $this->cache->getMulti( $checkSisterKeysByKey );
1179 $wrappedBySisterKey += array_fill_keys( $checkSisterKeysByKey,
false );
1183 foreach ( $checkSisterKeysByKey as $key => $checkSisterKey ) {
1184 $purge = $this->parsePurgeValue( $wrappedBySisterKey[$checkSisterKey] );
1185 if ( $purge ===
null ) {
1186 $wrapped = $this->makeCheckPurgeValue( $now, self::HOLDOFF_TTL_NONE, $purge );
1190 self::CHECK_KEY_TTL,
1191 $this->cache::WRITE_BACKGROUND
1195 $times[$key] = $purge[self::PURGE_TIME];
1235 $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1238 $purge = $this->makeCheckPurgeValue( $now, $holdoff );
1241 $keygroup = $this->determineKeyGroupForStats( $key );
1243 $this->stats->getCounter(
'wanobjectcache_check_total' )
1244 ->setLabel(
'keygroup', $keygroup )
1245 ->setLabel(
'result', ( $ok ?
'ok' :
'error' ) )
1246 ->copyToStatsdAt(
"wanobjectcache.$keygroup.ck_touch." . ( $ok ?
'ok' :
'error' ) )
1280 $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_TIMESTAMP );
1283 $keygroup = $this->determineKeyGroupForStats( $key );
1285 $this->stats->getCounter(
'wanobjectcache_reset_total' )
1286 ->setLabel(
'keygroup', $keygroup )
1287 ->setLabel(
'result', ( $ok ?
'ok' :
'error' ) )
1288 ->copyToStatsdAt(
"wanobjectcache.$keygroup.ck_reset." . ( $ok ?
'ok' :
'error' ) )
1596 $key, $ttl, $callback, array $opts = [], array $cbParams = []
1598 $version = $opts[
'version'] ??
null;
1599 $pcTTL = $opts[
'pcTTL'] ?? self::TTL_UNCACHEABLE;
1600 $pCache = ( $pcTTL >= 0 )
1601 ? $this->getProcessCache( $opts[
'pcGroup'] ?? self::PC_PRIMARY )
1607 if ( $pCache && $this->callbackDepth == 0 ) {
1608 $cached = $pCache->get( $key, $pcTTL,
false );
1609 if ( $cached !==
false ) {
1610 $this->logger->debug(
"getWithSetCallback($key): process cache hit" );
1615 [ $value, $valueVersion, $curAsOf ] = $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams );
1616 if ( $valueVersion !== $version ) {
1620 $this->logger->debug(
"getWithSetCallback($key): using variant key" );
1621 [ $value ] = $this->fetchOrRegenerate(
1622 $this->
makeGlobalKey(
'WANCache-key-variant', md5( $key ), (
string)$version ),
1625 [
'version' =>
null,
'minAsOf' => $curAsOf ] + $opts,
1631 if ( $pCache && $value !==
false ) {
1632 $pCache->set( $key, $value );
1654 private function fetchOrRegenerate( $key, $ttl, $callback, array $opts, array $cbParams ) {
1655 $checkKeys = $opts[
'checkKeys'] ?? [];
1657 $minAsOf = $opts[
'minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
1658 $hotTTR = $opts[
'hotTTR'] ?? self::HOT_TTR;
1659 $lowTTL = $opts[
'lowTTL'] ?? min( self::LOW_TTL, $ttl );
1660 $ageNew = $opts[
'ageNew'] ?? self::AGE_NEW;
1661 $touchedCb = $opts[
'touchedCallback'] ??
null;
1664 $keygroup = $this->determineKeyGroupForStats( $key );
1667 $curState = $this->
fetchKeys( [ $key ], $checkKeys, $startTime, $touchedCb )[$key];
1668 $curValue = $curState[self::RES_VALUE];
1671 if ( $this->isAcceptablyFreshValue( $curState, $graceTTL, $minAsOf ) ) {
1673 $this->stats->getTiming(
'wanobjectcache_getwithset_seconds' )
1674 ->setLabel(
'keygroup', $keygroup )
1675 ->setLabel(
'result',
'hit' )
1676 ->setLabel(
'reason',
'good' )
1677 ->copyToStatsdAt(
"wanobjectcache.$keygroup.hit.good" )
1680 return [ $curValue, $curState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1681 } elseif ( $this->scheduleAsyncRefresh( $key, $ttl, $callback, $opts, $cbParams ) ) {
1682 $this->logger->debug(
"fetchOrRegenerate($key): hit with async refresh" );
1684 $this->stats->getTiming(
'wanobjectcache_getwithset_seconds' )
1685 ->setLabel(
'keygroup', $keygroup )
1686 ->setLabel(
'result',
'hit' )
1687 ->setLabel(
'reason',
'refresh' )
1688 ->copyToStatsdAt(
"wanobjectcache.$keygroup.hit.refresh" )
1691 return [ $curValue, $curState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1693 $this->logger->debug(
"fetchOrRegenerate($key): hit with sync refresh" );
1697 $isKeyTombstoned = ( $curState[self::RES_TOMB_AS_OF] !== null );
1699 if ( $isKeyTombstoned ) {
1700 $volState = $this->getInterimValue( $key, $minAsOf, $startTime, $touchedCb );
1701 $volValue = $volState[self::RES_VALUE];
1703 $volState = $curState;
1704 $volValue = $curValue;
1712 $lastPurgeTime = max(
1714 $volState[self::RES_TOUCH_AS_OF],
1715 $curState[self::RES_TOMB_AS_OF],
1716 $curState[self::RES_CHECK_AS_OF]
1718 $safeMinAsOf = max( $minAsOf, $lastPurgeTime + self::TINY_POSITIVE );
1719 if ( $this->isExtremelyNewValue( $volState, $safeMinAsOf, $startTime ) ) {
1720 $this->logger->debug(
"fetchOrRegenerate($key): volatile hit" );
1722 $this->stats->getTiming(
'wanobjectcache_getwithset_seconds' )
1723 ->setLabel(
'keygroup', $keygroup )
1724 ->setLabel(
'result',
'hit' )
1725 ->setLabel(
'reason',
'volatile' )
1726 ->copyToStatsdAt(
"wanobjectcache.$keygroup.hit.volatile" )
1729 return [ $volValue, $volState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1732 $lockTSE = $opts[
'lockTSE'] ?? self::TSE_NONE;
1733 $busyValue = $opts[
'busyValue'] ??
null;
1735 $segmentable = $opts[
'segmentable'] ??
false;
1736 $version = $opts[
'version'] ??
null;
1739 $useRegenerationLock =
1750 $curState[self::RES_CUR_TTL] !==
null &&
1751 $curState[self::RES_CUR_TTL] <= 0 &&
1752 abs( $curState[self::RES_CUR_TTL] ) <= $lockTSE
1756 ( $busyValue !==
null && $volValue ===
false );
1761 $hasLock = $useRegenerationLock && $this->claimStampedeLock( $key );
1762 if ( $useRegenerationLock && !$hasLock ) {
1765 if ( $this->
isValid( $volValue, $volState[self::RES_AS_OF], $minAsOf ) ) {
1766 $this->logger->debug(
"fetchOrRegenerate($key): returning stale value" );
1768 $this->stats->getTiming(
'wanobjectcache_getwithset_seconds' )
1769 ->setLabel(
'keygroup', $keygroup )
1770 ->setLabel(
'result',
'hit' )
1771 ->setLabel(
'reason',
'stale' )
1772 ->copyToStatsdAt(
"wanobjectcache.$keygroup.hit.stale" )
1775 return [ $volValue, $volState[self::RES_VERSION], $curState[self::RES_AS_OF] ];
1776 } elseif ( $busyValue !==
null ) {
1777 $miss = is_infinite( $minAsOf ) ?
'renew' :
'miss';
1778 $this->logger->debug(
"fetchOrRegenerate($key): busy $miss" );
1780 $this->stats->getTiming(
'wanobjectcache_getwithset_seconds' )
1781 ->setLabel(
'keygroup', $keygroup )
1782 ->setLabel(
'result', $miss )
1783 ->setLabel(
'reason',
'busy' )
1784 ->copyToStatsdAt(
"wanobjectcache.$keygroup.$miss.busy" )
1787 $placeholderValue = $this->resolveBusyValue( $busyValue );
1789 return [ $placeholderValue, $version, $curState[self::RES_AS_OF] ];
1796 ++$this->callbackDepth;
1801 ( $curState[self::RES_VERSION] === $version ) ? $curValue : false,
1804 ( $curState[self::RES_VERSION] === $version ) ? $curState[self::RES_AS_OF] : null,
1808 --$this->callbackDepth;
1813 $walltime = max( $postCallbackTime - $preCallbackTime, 0.0 );
1815 $this->stats->getTiming(
'wanobjectcache_regen_seconds' )
1816 ->setLabel(
'keygroup', $keygroup )
1817 ->copyToStatsdAt(
"wanobjectcache.$keygroup.regen_walltime" )
1818 ->observe( 1e3 * $walltime );
1823 ( $value !==
false && $ttl >= 0 ) &&
1825 ( !$useRegenerationLock || $hasLock || $isKeyTombstoned )
1828 if ( $isKeyTombstoned ) {
1829 $this->setInterimValue(
1837 $this->setMainValue(
1844 $setOpts[
'lag'] ?? 0,
1846 $setOpts[
'since'] ?? $preCallbackTime,
1848 $setOpts[
'pending'] ??
false,
1852 ( $curValue ===
false )
1857 $this->yieldStampedeLock( $key, $hasLock );
1859 $miss = is_infinite( $minAsOf ) ?
'renew' :
'miss';
1860 $this->logger->debug(
"fetchOrRegenerate($key): $miss, new value computed" );
1862 $this->stats->getTiming(
'wanobjectcache_getwithset_seconds' )
1863 ->setLabel(
'keygroup', $keygroup )
1864 ->setLabel(
'result', $miss )
1865 ->setLabel(
'reason',
'compute' )
1866 ->copyToStatsdAt(
"wanobjectcache.$keygroup.$miss.compute" )
1869 return [ $value, $version, $curState[self::RES_AS_OF] ];
1876 private function claimStampedeLock( $key ) {
1877 $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX );
1879 return $this->cache->add( $checkSisterKey, 1, self::LOCK_TTL );
1886 private function yieldStampedeLock( $key, $hasLock ) {
1888 $checkSisterKey = $this->makeSisterKey( $key, self::TYPE_MUTEX );
1889 $this->cache->delete( $checkSisterKey, $this->cache::WRITE_BACKGROUND );
1903 private function makeSisterKeys( array $baseKeys,
string $type, ?
string $route =
null ) {
1905 foreach ( $baseKeys as $baseKey ) {
1906 $sisterKeys[] = $this->makeSisterKey( $baseKey, $type, $route );
1922 private function makeSisterKey(
string $baseKey,
string $typeChar, ?
string $route =
null ) {
1923 if ( $this->coalesceScheme === self::SCHEME_HASH_STOP ) {
1925 $sisterKey =
'WANCache:' . $baseKey .
'|#|' . $typeChar;
1928 $sisterKey =
'WANCache:{' . $baseKey .
'}:' . $typeChar;
1931 if ( $route !==
null ) {
1932 $sisterKey = $this->
prependRoute( $sisterKey, $route );
1950 private function isExtremelyNewValue( $res, $minAsOf, $now ) {
1951 if ( $res[self::RES_VALUE] ===
false || $res[self::RES_AS_OF] < $minAsOf ) {
1955 $age = $now - $res[self::RES_AS_OF];
1957 return ( $age < mt_rand( self::RECENT_SET_LOW_MS, self::RECENT_SET_HIGH_MS ) / 1e3 );
1969 private function getInterimValue( $key, $minAsOf, $now, $touchedCb ) {
1971 $interimSisterKey = $this->makeSisterKey( $key, self::TYPE_INTERIM );
1972 $wrapped = $this->cache->get( $interimSisterKey );
1973 $res = $this->unwrap( $wrapped, $now );
1974 if ( $res[self::RES_VALUE] !==
false && $res[self::RES_AS_OF] >= $minAsOf ) {
1975 if ( $touchedCb !==
null ) {
1978 $res[self::RES_TOUCH_AS_OF] = max(
1979 $touchedCb( $res[self::RES_VALUE] ),
1980 $res[self::RES_TOUCH_AS_OF]
1988 return $this->unwrap(
false, $now );
1999 private function setInterimValue(
2007 $ttl = max( self::INTERIM_KEY_TTL, (
int)$ttl );
2010 $wrapped = $this->wrap( $value, $ttl, $version, $now );
2012 $flags = $this->cache::WRITE_BACKGROUND;
2013 if ( $segmentable ) {
2014 $flags |= $this->cache::WRITE_ALLOW_SEGMENTS;
2017 return $this->cache->set(
2018 $this->makeSisterKey( $key, self::TYPE_INTERIM ),
2029 private function resolveBusyValue( $busyValue ) {
2030 return ( $busyValue instanceof Closure ) ? $busyValue() : $busyValue;
2099 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
2102 $this->warmupCache = $this->fetchWrappedValuesForWarmupCache(
2103 $this->getNonProcessCachedMultiKeys( $keyedIds, $opts ),
2104 $opts[
'checkKeys'] ?? []
2106 $this->warmupKeyMisses = 0;
2112 $proxyCb =
static function ( $oldValue, &$ttl, &$setOpts, $oldAsOf,
$params )
2115 return $callback(
$params[
'id'], $oldValue, $ttl, $setOpts, $oldAsOf );
2120 foreach ( $keyedIds as $key => $id ) {
2130 $this->warmupCache = [];
2202 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
2204 $checkKeys = $opts[
'checkKeys'] ?? [];
2205 $minAsOf = $opts[
'minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
2208 unset( $opts[
'lockTSE'] );
2209 unset( $opts[
'busyValue'] );
2212 $keysByIdGet = $this->getNonProcessCachedMultiKeys( $keyedIds, $opts );
2213 $this->warmupCache = $this->fetchWrappedValuesForWarmupCache( $keysByIdGet, $checkKeys );
2214 $this->warmupKeyMisses = 0;
2221 $resByKey = $this->
fetchKeys( $keysByIdGet, $checkKeys, $now );
2222 foreach ( $keysByIdGet as $id => $key ) {
2223 $res = $resByKey[$key];
2225 $res[self::RES_VALUE] ===
false ||
2226 $res[self::RES_CUR_TTL] < 0 ||
2227 $res[self::RES_AS_OF] < $minAsOf
2235 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
2236 $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
2238 $method = __METHOD__;
2243 $proxyCb =
function ( $oldValue, &$ttl, &$setOpts, $oldAsOf,
$params )
2244 use ( $callback, $newValsById, $newTTLsById, $newSetOpts, $method )
2248 if ( array_key_exists( $id, $newValsById ) ) {
2250 $newValue = $newValsById[$id];
2251 $ttl = $newTTLsById[$id];
2252 $setOpts = $newSetOpts;
2256 $ttls = [ $id => $ttl ];
2257 $result = $callback( [ $id ], $ttls, $setOpts );
2258 if ( !isset( $result[$id] ) ) {
2260 $this->logger->warning(
2261 $method .
' failed due to {id} not set in result {result}', [
2263 'result' => json_encode( $result )
2266 $newValue = $result[$id];
2275 foreach ( $keyedIds as $key => $id ) {
2285 $this->warmupCache = [];
2298 return $this->cache->makeGlobalKey( $keygroup, ...$components );
2308 public function makeKey( $keygroup, ...$components ) {
2309 return $this->cache->makeKey( $keygroup, ...$components );
2320 return hash_hmac(
'sha256', $component, $this->secret );
2376 foreach ( $ids as $id ) {
2378 if ( strlen( $id ) > 64 ) {
2379 $this->logger->warning( __METHOD__ .
": long ID '$id'; use hash256()" );
2381 $key = $keyCallback( $id, $this );
2383 if ( !isset( $idByKey[$key] ) ) {
2384 $idByKey[$key] = $id;
2385 } elseif ( (
string)$id !== (
string)$idByKey[$key] ) {
2386 throw new UnexpectedValueException(
2387 "Cache key collision; IDs ('$id','{$idByKey[$key]}') map to '$key'"
2392 return new ArrayIterator( $idByKey );
2431 if ( count( $ids ) !== count( $res ) ) {
2434 $ids = array_keys( array_fill_keys( $ids,
true ) );
2435 if ( count( $ids ) !== count( $res ) ) {
2436 throw new UnexpectedValueException(
"Multi-key result does not match ID list" );
2440 return array_combine( $ids, $res );
2450 return $this->cache->watchErrors();
2471 $code = $this->cache->getLastError( $watchPoint );
2490 $this->cache->clearLastError();
2499 $this->processCaches = [];
2532 return $this->cache->getQoS( $flag );
2598 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
2600 $mtime = (int)$mtime;
2601 if ( $mtime <= 0 ) {
2608 return (
int)min( $maxTTL, max( $minTTL, $factor * $age ) );
2618 return $this->warmupKeyMisses;
2636 if ( $this->broadcastRoute !==
null ) {
2637 $routeKey = $this->
prependRoute( $sisterKey, $this->broadcastRoute );
2639 $routeKey = $sisterKey;
2642 return $this->cache->set(
2646 $this->cache::WRITE_BACKGROUND
2659 if ( $this->broadcastRoute !==
null ) {
2660 $routeKey = $this->
prependRoute( $sisterKey, $this->broadcastRoute );
2662 $routeKey = $sisterKey;
2665 return $this->cache->delete( $routeKey, $this->cache::WRITE_BACKGROUND );
2674 if ( $sisterKey[0] ===
'/' ) {
2675 throw new RuntimeException(
"Sister key '$sisterKey' already contains a route." );
2678 return $route . $sisterKey;
2692 private function scheduleAsyncRefresh( $key, $ttl, $callback, array $opts, array $cbParams ) {
2693 if ( !$this->asyncHandler ) {
2701 $func(
function () use ( $key, $ttl, $callback, $opts, $cbParams ) {
2702 $opts[
'minAsOf'] = INF;
2704 $this->fetchOrRegenerate( $key, $ttl, $callback, $opts, $cbParams );
2705 }
catch ( Exception $e ) {
2707 $this->logger->error(
'Async refresh failed for {key}', [
2727 private function isAcceptablyFreshValue( $res, $graceTTL, $minAsOf ) {
2728 if ( !$this->
isValid( $res[self::RES_VALUE], $res[self::RES_AS_OF], $minAsOf ) ) {
2733 $curTTL = $res[self::RES_CUR_TTL];
2734 if ( $curTTL > 0 ) {
2740 $curGraceTTL = $graceTTL + $curTTL;
2742 return ( $curGraceTTL > 0 )
2760 $curTTL = $res[self::RES_CUR_TTL];
2761 $logicalTTL = $res[self::RES_TTL];
2762 $asOf = $res[self::RES_AS_OF];
2786 if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
2790 $age = $now - $asOf;
2791 $timeOld = $age - $ageNew;
2792 if ( $timeOld <= 0 ) {
2796 $popularHitsPerSec = 1;
2800 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
2804 $chance = 1 / ( $popularHitsPerSec * $refreshWindowSec );
2806 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
2808 return ( mt_rand( 1, 1_000_000_000 ) <= 1_000_000_000 * $chance );
2830 if ( $lowTTL <= 0 ) {
2835 $effectiveLowTTL = min( $lowTTL, $logicalTTL ?: INF );
2838 $timeOld = $effectiveLowTTL - $curTTL;
2839 if ( $timeOld <= 0 || $timeOld >= $effectiveLowTTL ) {
2844 $ttrRatio = $timeOld / $effectiveLowTTL;
2847 $chance = $ttrRatio ** 4;
2849 return ( mt_rand( 1, 1_000_000_000 ) <= 1_000_000_000 * $chance );
2860 protected function isValid( $value, $asOf, $minAsOf ) {
2861 return ( $value !==
false && $asOf >= $minAsOf );
2871 private function wrap( $value, $ttl, $version, $now ) {
2875 self::FLD_FORMAT_VERSION => self::VERSION,
2876 self::FLD_VALUE => $value,
2877 self::FLD_TTL => $ttl,
2878 self::FLD_TIME => $now
2880 if ( $version !==
null ) {
2881 $wrapped[self::FLD_VALUE_VERSION] = $version;
2901 private function unwrap( $wrapped, $now ) {
2905 self::RES_VALUE =>
false,
2906 self::RES_VERSION =>
null,
2907 self::RES_AS_OF =>
null,
2908 self::RES_TTL =>
null,
2909 self::RES_TOMB_AS_OF =>
null,
2911 self::RES_CHECK_AS_OF =>
null,
2912 self::RES_TOUCH_AS_OF =>
null,
2913 self::RES_CUR_TTL => null
2916 if ( is_array( $wrapped ) ) {
2919 ( $wrapped[self::FLD_FORMAT_VERSION] ??
null ) === self::VERSION &&
2920 $wrapped[self::FLD_TIME] >= $this->epoch
2922 if ( $wrapped[self::FLD_TTL] > 0 ) {
2924 $age = $now - $wrapped[self::FLD_TIME];
2925 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
2930 $res[self::RES_VALUE] = $wrapped[self::FLD_VALUE];
2931 $res[self::RES_VERSION] = $wrapped[self::FLD_VALUE_VERSION] ??
null;
2932 $res[self::RES_AS_OF] = $wrapped[self::FLD_TIME];
2933 $res[self::RES_CUR_TTL] = $curTTL;
2934 $res[self::RES_TTL] = $wrapped[self::FLD_TTL];
2938 $purge = $this->parsePurgeValue( $wrapped );
2939 if ( $purge !==
null ) {
2941 $curTTL = min( $purge[self::PURGE_TIME] - $now, self::TINY_NEGATIVE );
2942 $res[self::RES_CUR_TTL] = $curTTL;
2943 $res[self::RES_TOMB_AS_OF] = $purge[self::PURGE_TIME];
2955 private function determineKeyGroupForStats( $key ) {
2956 $parts = explode(
':', $key, 3 );
2959 return strtr( $parts[1] ?? $parts[0],
'.',
'_' );
2970 private function parsePurgeValue( $value ) {
2971 if ( !is_string( $value ) ) {
2975 $segments = explode(
':', $value, 3 );
2976 $prefix = $segments[0];
2977 if ( $prefix !== self::PURGE_VAL_PREFIX ) {
2982 $timestamp = (float)$segments[1];
2984 $holdoff = isset( $segments[2] ) ? (int)$segments[2] : self::
HOLDOFF_TTL;
2986 if ( $timestamp < $this->epoch ) {
2991 return [ self::PURGE_TIME => $timestamp, self::PURGE_HOLDOFF => $holdoff ];
2998 private function makeTombstonePurgeValue(
float $timestamp ) {
2999 return self::PURGE_VAL_PREFIX .
':' . (int)$timestamp;
3008 private function makeCheckPurgeValue(
float $timestamp,
int $holdoff, ?array &$purge =
null ) {
3009 $normalizedTime = (int)$timestamp;
3011 $purge = [ self::PURGE_TIME => (float)$normalizedTime, self::PURGE_HOLDOFF => $holdoff ];
3013 return self::PURGE_VAL_PREFIX .
":$normalizedTime:$holdoff";
3020 private function getProcessCache( $group ) {
3021 if ( !isset( $this->processCaches[$group] ) ) {
3022 [ , $size ] = explode(
':', $group );
3023 $this->processCaches[$group] =
new MapCacheLRU( (
int)$size );
3024 if ( $this->wallClockOverride !==
null ) {
3025 $this->processCaches[$group]->setMockTime( $this->wallClockOverride );
3029 return $this->processCaches[$group];
3037 private function getNonProcessCachedMultiKeys( ArrayIterator $keys, array $opts ) {
3038 $pcTTL = $opts[
'pcTTL'] ?? self::TTL_UNCACHEABLE;
3041 if ( $pcTTL > 0 && $this->callbackDepth == 0 ) {
3042 $pCache = $this->getProcessCache( $opts[
'pcGroup'] ?? self::PC_PRIMARY );
3043 foreach ( $keys as $key => $id ) {
3044 if ( !$pCache->has( $key, $pcTTL ) ) {
3045 $keysMissing[$id] = $key;
3050 return $keysMissing;
3059 private function fetchWrappedValuesForWarmupCache( array $keys, array $checkKeys ) {
3065 $sisterKeys = $this->makeSisterKeys( $keys, self::TYPE_VALUE );
3067 foreach ( $checkKeys as $i => $checkKeyOrKeyGroup ) {
3069 if ( is_int( $i ) ) {
3071 $sisterKeys[] = $this->makeSisterKey( $checkKeyOrKeyGroup, self::TYPE_TIMESTAMP );
3074 foreach ( (array)$checkKeyOrKeyGroup as $checkKey ) {
3075 $sisterKeys[] = $this->makeSisterKey( $checkKey, self::TYPE_TIMESTAMP );
3080 $wrappedBySisterKey = $this->cache->getMulti( $sisterKeys );
3081 $wrappedBySisterKey += array_fill_keys( $sisterKeys,
false );
3083 return $wrappedBySisterKey;
3091 private function timeSinceLoggedMiss( $key, $now ) {
3093 for ( end( $this->missLog ); $miss = current( $this->missLog ); prev( $this->missLog ) ) {
3094 if ( $miss[0] === $key ) {
3095 return ( $now - $miss[1] );
3107 return $this->wallClockOverride ?: microtime(
true );
3115 $this->wallClockOverride =& $time;
3116 $this->cache->setMockTime( $time );
3117 foreach ( $this->processCaches as $pCache ) {
3118 $pCache->setMockTime( $time );