22use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface;
23use Psr\Log\LoggerAwareInterface;
24use Psr\Log\LoggerInterface;
25use Psr\Log\NullLogger;
255 $this->
cache = $params[
'cache'];
256 $this->region =
$params[
'region'] ??
'main';
257 $this->cluster =
$params[
'cluster'] ??
'wan-main';
258 $this->mcrouterAware = !empty(
$params[
'mcrouterAware'] );
259 $this->epoch =
$params[
'epoch'] ?? 1.0;
263 $this->asyncHandler =
$params[
'asyncHandler'] ??
null;
270 $this->logger = $logger;
331 final public function get(
332 $key, &$curTTL =
null,
array $checkKeys = [], &$info =
null
334 $curTTLs = self::PASS_BY_REF;
335 $infoByKey = self::PASS_BY_REF;
336 $values = $this->
getMulti( [ $key ], $curTTLs, $checkKeys, $infoByKey );
337 $curTTL = $curTTLs[$key] ??
null;
338 if ( $info === self::PASS_BY_REF ) {
340 'asOf' => $infoByKey[$key][
'asOf'] ??
null,
341 'tombAsOf' => $infoByKey[$key][
'tombAsOf'] ??
null,
342 'lastCKPurge' => $infoByKey[$key][
'lastCKPurge'] ??
null
345 $info = $infoByKey[$key][
'asOf'] ??
null;
348 return $values[$key] ??
false;
373 array $checkKeys = [],
380 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
381 $valueKeys = self::prefixCacheKeys(
$keys, self::VALUE_KEY_PREFIX );
383 $checkKeysForAll = [];
384 $checkKeysByKey = [];
386 foreach ( $checkKeys
as $i => $checkKeyGroup ) {
387 $prefixed = self::prefixCacheKeys( (
array)$checkKeyGroup, self::TIME_KEY_PREFIX );
388 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
390 if ( is_int( $i ) ) {
391 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
393 $checkKeysByKey[$i] = $prefixed;
398 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
399 if ( $this->warmupCache ) {
400 $wrappedValues = array_intersect_key( $this->warmupCache, array_flip( $keysGet ) );
401 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) );
402 $this->warmupKeyMisses += count( $keysGet );
407 $wrappedValues += $this->
cache->getMulti( $keysGet );
413 $purgeValuesForAll = $this->
processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
414 $purgeValuesByKey = [];
415 foreach ( $checkKeysByKey
as $cacheKey => $checks ) {
416 $purgeValuesByKey[$cacheKey] =
421 foreach ( $valueKeys
as $vKey ) {
422 $key = substr( $vKey, $vPrefixLen );
423 list(
$value, $curTTL, $asOf, $tombAsOf ) = isset( $wrappedValues[$vKey] )
424 ? $this->
unwrap( $wrappedValues[$vKey], $now )
425 : [
false,
null,
null,
null ];
428 $purgeValues = $purgeValuesForAll;
429 if ( isset( $purgeValuesByKey[$key] ) ) {
430 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
434 foreach ( $purgeValues
as $purge ) {
435 $lastCKPurge = max( $purge[self::FLD_TIME], $lastCKPurge );
436 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
437 if (
$value !==
false && $safeTimestamp >= $asOf ) {
439 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
441 $curTTL = min( $curTTL, $ago );
448 if ( $curTTL !==
null ) {
449 $curTTLs[$key] = $curTTL;
452 $infoByKey[$key] = ( $info === self::PASS_BY_REF )
453 ? [
'asOf' => $asOf,
'tombAsOf' => $tombAsOf,
'lastCKPurge' => $lastCKPurge ]
471 foreach ( $timeKeys
as $timeKey ) {
472 $purge = isset( $wrappedValues[$timeKey] )
475 if ( $purge ===
false ) {
478 $this->
cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
481 $purgeValues[] = $purge;
554 final public function set( $key,
$value, $ttl = self::TTL_INDEFINITE,
array $opts = [] ) {
556 $lockTSE = $opts[
'lockTSE'] ?? self::TSE_NONE;
557 $staleTTL = $opts[
'staleTTL'] ?? self::STALE_TTL_NONE;
558 $age = isset( $opts[
'since'] ) ? max( 0, $now - $opts[
'since'] ) : 0;
559 $creating = $opts[
'creating'] ??
false;
560 $lag = $opts[
'lag'] ?? 0;
563 if ( !empty( $opts[
'pending'] ) ) {
565 'Rejected set() for {cachekey} due to pending writes.',
566 [
'cachekey' => $key ]
574 if ( $lag ===
false || ( $lag + $age ) > self::MAX_READ_LAG ) {
576 if ( $age > self::MAX_READ_LAG ) {
577 if ( $lockTSE >= 0 ) {
579 $logicalTTL = self::TTL_SECOND;
581 'Lowered set() TTL for {cachekey} due to snapshot lag.',
582 [
'cachekey' => $key,
'lag' => $lag,
'age' => $age ]
586 'Rejected set() for {cachekey} due to snapshot lag.',
587 [
'cachekey' => $key,
'lag' => $lag,
'age' => $age ]
593 } elseif ( $lag ===
false || $lag > self::MAX_READ_LAG ) {
594 if ( $lockTSE >= 0 ) {
595 $logicalTTL = min( $ttl ?: INF, self::TTL_LAGGED );
597 $ttl = min( $ttl ?: INF, self::TTL_LAGGED );
599 $this->logger->warning(
600 'Lowered set() TTL for {cachekey} due to replication lag.',
601 [
'cachekey' => $key,
'lag' => $lag,
'age' => $age ]
604 } elseif ( $lockTSE >= 0 ) {
606 $logicalTTL = self::TTL_SECOND;
608 'Lowered set() TTL for {cachekey} due to high read lag.',
609 [
'cachekey' => $key,
'lag' => $lag,
'age' => $age ]
613 'Rejected set() for {cachekey} due to high read lag.',
614 [
'cachekey' => $key,
'lag' => $lag,
'age' => $age ]
622 $wrapped = $this->
wrap(
$value, $logicalTTL ?: $ttl, $now );
623 $storeTTL = $ttl + $staleTTL;
626 $ok = $this->
cache->add( self::VALUE_KEY_PREFIX . $key, $wrapped, $storeTTL );
628 $ok = $this->
cache->merge(
629 self::VALUE_KEY_PREFIX . $key,
630 function (
$cache, $key, $cWrapped )
use ( $wrapped ) {
632 return ( is_string( $cWrapped ) ) ?
false : $wrapped;
703 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
706 $ok = $this->
relayDelete( self::VALUE_KEY_PREFIX . $key );
709 $ok = $this->
relayPurge( self::VALUE_KEY_PREFIX . $key, $ttl, self::HOLDOFF_NONE );
713 $this->stats->increment(
"wanobjectcache.$kClass.delete." . ( $ok ?
'ok' :
'error' ) );
805 $rawKeys[$key] = self::TIME_KEY_PREFIX . $key;
808 $rawValues = $this->
cache->getMulti( $rawKeys );
809 $rawValues += array_fill_keys( $rawKeys,
false );
812 foreach ( $rawKeys
as $key => $rawKey ) {
814 if ( $purge !==
false ) {
815 $time = $purge[self::FLD_TIME];
827 $times[$key] =
$time;
869 $ok = $this->
relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
872 $this->stats->increment(
"wanobjectcache.$kClass.ck_touch." . ( $ok ?
'ok' :
'error' ) );
906 $ok = $this->
relayDelete( self::TIME_KEY_PREFIX . $key );
909 $this->stats->increment(
"wanobjectcache.$kClass.ck_reset." . ( $ok ?
'ok' :
'error' ) );
1216 $pcTTL = $opts[
'pcTTL'] ?? self::TTL_UNCACHEABLE;
1221 if ( $pcTTL >= 0 && $this->callbackDepth == 0 ) {
1222 $group = $opts[
'pcGroup'] ?? self::PC_PRIMARY;
1224 $value = $procCache->has( $key, $pcTTL ) ? $procCache->get( $key ) :
false;
1230 if (
$value ===
false ) {
1232 if ( isset( $opts[
'version'] ) ) {
1233 $version = $opts[
'version'];
1238 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1239 use ( $callback, $version ) {
1240 if ( is_array( $oldValue )
1241 && array_key_exists( self::VFLD_DATA, $oldValue )
1242 && array_key_exists( self::VFLD_VERSION, $oldValue )
1243 && $oldValue[self::VFLD_VERSION] === $version
1245 $oldData = $oldValue[self::VFLD_DATA];
1253 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
1254 self::VFLD_VERSION => $version
1260 if ( $cur[self::VFLD_VERSION] === $version ) {
1262 $value = $cur[self::VFLD_DATA];
1267 $this->
makeGlobalKey(
'WANCache-key-variant', md5( $key ), $version ),
1271 [
'version' =>
null,
'minAsOf' => $asOf ] + $opts
1279 if ( $procCache &&
$value !==
false ) {
1280 $procCache->set( $key,
$value );
1301 $lowTTL = $opts[
'lowTTL'] ?? min( self::LOW_TTL, $ttl );
1302 $lockTSE = $opts[
'lockTSE'] ?? self::TSE_NONE;
1303 $staleTTL = $opts[
'staleTTL'] ?? self::STALE_TTL_NONE;
1304 $graceTTL = $opts[
'graceTTL'] ?? self::GRACE_TTL_NONE;
1305 $checkKeys = $opts[
'checkKeys'] ?? [];
1306 $busyValue = $opts[
'busyValue'] ??
null;
1307 $popWindow = $opts[
'hotTTR'] ?? self::HOT_TTR;
1308 $ageNew = $opts[
'ageNew'] ?? self::AGE_NEW;
1309 $minTime = $opts[
'minAsOf'] ?? self::MIN_TIMESTAMP_NONE;
1310 $needsVersion = isset( $opts[
'version'] );
1311 $touchedCb = $opts[
'touchedCallback'] ??
null;
1317 $curTTL = self::PASS_BY_REF;
1318 $curInfo = self::PASS_BY_REF;
1319 $curValue = $this->
get( $key, $curTTL, $checkKeys, $curInfo );
1321 list( $curTTL, $LPT ) = $this->
resolveCTL( $curValue, $curTTL, $curInfo, $touchedCb );
1324 $asOf = $curInfo[
'asOf'];
1331 $preemptiveRefresh = (
1336 if ( !$preemptiveRefresh ) {
1337 $this->stats->increment(
"wanobjectcache.$kClass.hit.good" );
1341 $this->stats->increment(
"wanobjectcache.$kClass.hit.refresh" );
1347 $isKeyTombstoned = ( $curInfo[
'tombAsOf'] !==
null );
1348 if ( $isKeyTombstoned ) {
1358 $this->
isValid(
$value, $needsVersion, $asOf, $minTime, $LPT ) &&
1361 $this->stats->increment(
"wanobjectcache.$kClass.hit.volatile" );
1377 ( $curTTL !==
null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE ) ||
1380 ( $busyValue !==
null &&
$value ===
false );
1385 if ( $this->
cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
1388 } elseif ( $this->
isValid(
$value, $needsVersion, $asOf, $minTime ) ) {
1390 $this->stats->increment(
"wanobjectcache.$kClass.hit.stale" );
1395 if ( $busyValue !==
null ) {
1397 $miss = is_infinite( $minTime ) ?
'renew' :
'miss';
1398 $this->stats->increment(
"wanobjectcache.$kClass.$miss.busy" );
1400 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
1405 if ( !is_callable( $callback ) ) {
1406 throw new InvalidArgumentException(
"Invalid cache miss callback provided." );
1412 ++$this->callbackDepth;
1414 $value = call_user_func_array( $callback, [ $curValue, &$ttl, &$setOpts, $asOf ] );
1416 --$this->callbackDepth;
1418 $valueIsCacheable = (
$value !==
false && $ttl >= 0 );
1420 if ( $valueIsCacheable ) {
1422 $this->stats->timing(
"wanobjectcache.$kClass.regen_set_delay", 1000 * $ago );
1424 if ( $isKeyTombstoned ) {
1427 $tempTTL = max( self::INTERIM_KEY_TTL, (
int)$lockTSE );
1430 } elseif ( !$useMutex || $hasLock ) {
1432 $setOpts[
'creating'] = ( $curValue ===
false );
1434 $setOpts[
'lockTSE'] = $lockTSE;
1435 $setOpts[
'staleTTL'] = $staleTTL;
1437 $setOpts += [
'since' => $preCallbackTime ];
1439 $this->
set( $key,
$value, $ttl, $setOpts );
1445 $this->
cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, (
int)$initialTime - 60 );
1448 $miss = is_infinite( $minTime ) ?
'renew' :
'miss';
1449 $this->stats->increment(
"wanobjectcache.$kClass.$miss.compute" );
1459 return ( $age < mt_rand( self::RECENT_SET_LOW_MS, self::RECENT_SET_HIGH_MS ) / 1e3 );
1477 if ( $lockTSE < 0 || $hasLock ) {
1479 } elseif ( $elapsed <= self::SET_DELAY_HIGH_MS * 1e3 ) {
1483 $this->
cache->clearLastError();
1485 !$this->
cache->add( self::COOLOFF_KEY_PREFIX . $key, 1, self::COOLOFF_TTL ) &&
1489 $this->stats->increment(
"wanobjectcache.$kClass.cooloff_bounce" );
1506 if ( $touchedCallback ===
null ||
$value ===
false ) {
1507 return [ $curTTL, max( $curInfo[
'tombAsOf'], $curInfo[
'lastCKPurge'] ) ];
1510 if ( !is_callable( $touchedCallback ) ) {
1511 throw new InvalidArgumentException(
"Invalid expiration callback provided." );
1514 $touched = $touchedCallback(
$value );
1515 if ( $touched !==
null && $touched >= $curInfo[
'asOf'] ) {
1516 $curTTL = min( $curTTL, self::TINY_NEGATIVE, $curInfo[
'asOf'] - $touched );
1519 return [ $curTTL, max( $curInfo[
'tombAsOf'], $curInfo[
'lastCKPurge'], $touched ) ];
1530 if ( $touchedCallback ===
null ||
$value ===
false ) {
1534 if ( !is_callable( $touchedCallback ) ) {
1535 throw new InvalidArgumentException(
"Invalid expiration callback provided." );
1538 return max( $touchedCallback(
$value ), $lastPurge );
1549 return [
false,
null ];
1552 $wrapped = $this->
cache->get( self::INTERIM_KEY_PREFIX . $key );
1554 $valueAsOf = $wrapped[self::FLD_TIME] ??
null;
1555 if ( $this->
isValid(
$value, $versioned, $valueAsOf, $minTime ) ) {
1556 return [
$value, $valueAsOf ];
1559 return [
false,
null ];
1569 $wrapped = $this->
wrap(
$value, $tempTTL, $newAsOf );
1571 $this->
cache->merge(
1572 self::INTERIM_KEY_PREFIX . $key,
1573 function ()
use ( $wrapped ) {
1648 ArrayIterator $keyedIds, $ttl, callable $callback,
array $opts = []
1650 $valueKeys = array_keys( $keyedIds->getArrayCopy() );
1651 $checkKeys = $opts[
'checkKeys'] ?? [];
1652 $pcTTL = $opts[
'pcTTL'] ?? self::TTL_UNCACHEABLE;
1659 $this->warmupKeyMisses = 0;
1663 $func =
function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
use ( $callback, &$id ) {
1664 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1668 foreach ( $keyedIds
as $key => $id ) {
1672 $this->warmupCache = [];
1743 ArrayIterator $keyedIds, $ttl, callable $callback,
array $opts = []
1745 $idsByValueKey = $keyedIds->getArrayCopy();
1746 $valueKeys = array_keys( $idsByValueKey );
1747 $checkKeys = $opts[
'checkKeys'] ?? [];
1748 $pcTTL = $opts[
'pcTTL'] ?? self::TTL_UNCACHEABLE;
1749 unset( $opts[
'lockTSE'] );
1750 unset( $opts[
'busyValue'] );
1755 $this->warmupKeyMisses = 0;
1763 $curByKey = $this->
getMulti( $keysGet, $curTTLs, $checkKeys, $asOfs );
1764 foreach ( $keysGet
as $key ) {
1765 if ( !array_key_exists( $key, $curByKey ) || $curTTLs[$key] < 0 ) {
1766 $idsRegen[] = $idsByValueKey[$key];
1772 $newTTLsById = array_fill_keys( $idsRegen, $ttl );
1773 $newValsById = $idsRegen ? $callback( $idsRegen, $newTTLsById, $newSetOpts ) : [];
1777 $func =
function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
1778 use ( $callback, &$id, $newValsById, $newTTLsById, $newSetOpts )
1780 if ( array_key_exists( $id, $newValsById ) ) {
1782 $newValue = $newValsById[$id];
1783 $ttl = $newTTLsById[$id];
1784 $setOpts = $newSetOpts;
1788 $ttls = [ $id => $ttl ];
1789 $newValue = $callback( [ $id ], $ttls, $setOpts )[$id];
1798 foreach ( $idsByValueKey
as $key => $id ) {
1802 $this->warmupCache = [];
1819 final public function reap( $key, $purgeTimestamp, &$isStale =
false ) {
1820 $minAsOf = $purgeTimestamp + self::HOLDOFF_TTL;
1821 $wrapped = $this->
cache->get( self::VALUE_KEY_PREFIX . $key );
1822 if ( is_array( $wrapped ) && $wrapped[self::FLD_TIME] < $minAsOf ) {
1824 $this->logger->warning(
"Reaping stale value key '$key'." );
1825 $ttlReap = self::HOLDOFF_TTL;
1826 $ok = $this->
cache->changeTTL( self::VALUE_KEY_PREFIX . $key, $ttlReap );
1828 $this->logger->error(
"Could not complete reap of key '$key'." );
1848 final public function reapCheckKey( $key, $purgeTimestamp, &$isStale =
false ) {
1850 if ( $purge && $purge[self::FLD_TIME] < $purgeTimestamp ) {
1852 $this->logger->warning(
"Reaping stale check key '$key'." );
1853 $ok = $this->
cache->changeTTL( self::TIME_KEY_PREFIX . $key, self::TTL_SECOND );
1855 $this->logger->error(
"Could not complete reap of check key '$key'." );
1873 public function makeKey( $class, $component =
null ) {
1874 return $this->
cache->makeKey( ...func_get_args() );
1885 return $this->
cache->makeGlobalKey( ...func_get_args() );
1896 foreach ( $entities
as $entity ) {
1897 $map[$keyFunc( $entity, $this )] = $entity;
1900 return new ArrayIterator( $map );
1911 return self::ERR_NONE;
1913 return self::ERR_NO_RESPONSE;
1915 return self::ERR_UNREACHABLE;
1917 return self::ERR_UNEXPECTED;
1925 $this->
cache->clearLastError();
1934 $this->processCaches = [];
1967 return $this->
cache->getQoS( $flag );
2033 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = 0.2 ) {
2034 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
2035 $mtime = (int)$mtime;
2038 if ( !is_int( $mtime ) || $mtime <= 0 ) {
2044 return (
int)min( $maxTTL, max( $minTTL, $factor * $age ) );
2052 return $this->warmupKeyMisses;
2066 if ( $this->mcrouterAware ) {
2069 $ok = $this->
cache->set(
2070 "/*/{$this->cluster}/{$key}",
2076 $ok = $this->
cache->set(
2093 if ( $this->mcrouterAware ) {
2096 $ok = $this->
cache->delete(
"/*/{$this->cluster}/{$key}" );
2099 $ok = $this->
cache->delete( $key );
2113 if ( !$this->asyncHandler ) {
2117 $func = $this->asyncHandler;
2118 $func(
function ()
use ( $key, $ttl, $callback, $opts ) {
2120 $opts[
'minAsOf'] = INF;
2141 if ( $curTTL > 0 ) {
2143 } elseif ( $graceTTL <= 0 ) {
2147 $ageStale = abs( $curTTL );
2148 $curGTTL = ( $graceTTL - $ageStale );
2149 if ( $curGTTL <= 0 ) {
2171 if ( $lowTTL <= 0 ) {
2173 } elseif ( $curTTL >= $lowTTL ) {
2175 } elseif ( $curTTL <= 0 ) {
2179 $chance = ( 1 - $curTTL / $lowTTL );
2181 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
2200 if ( $ageNew < 0 || $timeTillRefresh <= 0 ) {
2204 $age = $now - $asOf;
2205 $timeOld = $age - $ageNew;
2206 if ( $timeOld <= 0 ) {
2213 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
2217 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
2220 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
2222 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
2235 protected function isValid(
$value, $versioned, $asOf, $minTime, $purgeTime =
null ) {
2237 $safeMinTime = max( $minTime, $purgeTime + self::TINY_POSTIVE );
2239 if (
$value ===
false ) {
2241 } elseif ( $versioned && !isset(
$value[self::VFLD_VERSION] ) ) {
2243 } elseif ( $safeMinTime > 0 && $asOf < $minTime ) {
2260 self::FLD_VERSION => self::VERSION,
2261 self::FLD_VALUE =>
$value,
2262 self::FLD_TTL => $ttl,
2263 self::FLD_TIME => $now
2276 protected function unwrap( $wrapped, $now ) {
2279 if ( $purge !==
false ) {
2281 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
2282 return [
false, $curTTL,
null, $purge[self::FLD_TIME] ];
2285 if ( !is_array( $wrapped )
2286 || !isset( $wrapped[self::FLD_VERSION] )
2287 || $wrapped[self::FLD_VERSION] !== self::VERSION
2289 return [
false,
null,
null,
null ];
2292 if ( $wrapped[self::FLD_TTL] > 0 ) {
2294 $age = $now - $wrapped[self::FLD_TIME];
2295 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
2301 if ( $wrapped[self::FLD_TIME] < $this->epoch ) {
2303 return [
false,
null,
null,
null ];
2306 return [ $wrapped[self::FLD_VALUE], $curTTL, $wrapped[self::FLD_TIME],
null ];
2317 $res[] = $prefix . $key;
2328 $parts = explode(
':', $key );
2330 return $parts[1] ?? $parts[0];
2339 if ( !is_string(
$value ) ) {
2343 $segments = explode(
':',
$value, 3 );
2344 if ( !isset( $segments[0] ) || !isset( $segments[1] )
2345 ||
"{$segments[0]}:" !== self::PURGE_VAL_PREFIX
2350 if ( !isset( $segments[2] ) ) {
2352 $segments[2] = self::HOLDOFF_TTL;
2355 if ( $segments[1] < $this->epoch ) {
2361 self::FLD_TIME => (float)$segments[1],
2362 self::FLD_HOLDOFF => (
int)$segments[2],
2372 return self::PURGE_VAL_PREFIX . (float)$timestamp .
':' . (
int)$holdoff;
2380 if ( !isset( $this->processCaches[$group] ) ) {
2381 list( , $n ) = explode(
':', $group );
2382 $this->processCaches[$group] =
new MapCacheLRU( (
int)$n );
2385 return $this->processCaches[$group];
2396 if ( isset( $opts[
'pcTTL'] ) && $opts[
'pcTTL'] > 0 && $this->callbackDepth == 0 ) {
2397 $pcGroup = $opts[
'pcGroup'] ?? self::PC_PRIMARY;
2400 if ( $procCache->has( $key, $pcTTL ) ) {
2401 $keysFound[] = $key;
2406 return array_diff(
$keys, $keysFound );
2422 $keysWarmUp[] = self::VALUE_KEY_PREFIX . $key;
2425 foreach ( $checkKeys
as $i => $checkKeyOrKeys ) {
2426 if ( is_int( $i ) ) {
2428 $keysWarmUp[] = self::TIME_KEY_PREFIX . $checkKeyOrKeys;
2431 $keysWarmUp = array_merge(
2433 self::prefixCacheKeys( $checkKeyOrKeys, self::TIME_KEY_PREFIX )
2449 if ( $this->wallClockOverride ) {
2450 return $this->wallClockOverride;
2453 $clockTime = (float)time();
2459 return max( microtime(
true ), $clockTime );
2467 $this->wallClockOverride =&
$time;
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Class representing a cache/ephemeral data store.
A BagOStuff object with no objects in it.
Handles a simple LRU key/value map with a maximum number of entries.
Multi-datacenter aware caching interface.
int $callbackDepth
Callback stack depth for getWithSetCallback()
const TINY_NEGATIVE
Tiny negative float to use when CTL comes up >= 0 due to clock skew.
const HOLDOFF_TTL
Seconds to tombstone keys on delete()
const HOT_TTR
The time length of the "popularity" refresh window for hot keys.
__construct(array $params)
resolveCTL( $value, $curTTL, $curInfo, $touchedCallback)
unwrap( $wrapped, $now)
Do not use this method outside WANObjectCache.
checkAndSetCooloff( $key, $kClass, $elapsed, $lockTSE, $hasLock)
worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now)
Check if a key is due for randomized regeneration due to its popularity.
determineKeyClassForStats( $key)
touchCheckKey( $key, $holdoff=self::HOLDOFF_TTL)
Purge a "check" key from all datacenters, invalidating keys that use it.
adaptiveTTL( $mtime, $maxTTL, $minTTL=30, $factor=0.2)
Get a TTL that is higher for objects that have not changed recently.
string $cluster
Cache cluster name for mcrouter use.
const GRACE_TTL_NONE
Idiom for set()/getWithSetCallback() for "no post-expired grace period".
getInterimValue( $key, $versioned, $minTime)
isVolatileValueAgeNegligible( $age)
int $warmupKeyMisses
Key fetched.
float null $wallClockOverride
scheduleAsyncRefresh( $key, $ttl, $callback, $opts)
mixed[] $warmupCache
Temporary warm-up cache.
const VERSION
Cache format version number.
const TTL_UNCACHEABLE
Idiom for getWithSetCallback() callbacks to avoid calling set()
const LOW_TTL
Default remaining TTL at which to consider pre-emptive regeneration.
getMulti(array $keys, &$curTTLs=[], array $checkKeys=[], &$info=null)
Fetch the value of several keys from cache.
relayPurge( $key, $ttl, $holdoff)
Do the actual async bus purge of a key.
getLastError()
Get the "last error" registered; clearLastError() should be called manually.
BagOStuff $cache
The local datacenter cache.
getNonProcessCachedKeys(array $keys, array $opts, $pcTTL)
isValid( $value, $versioned, $asOf, $minTime, $purgeTime=null)
Check if $value is not false, versioned (if needed), and not older than $minTime (if set)
processCheckKeys(array $timeKeys, array $wrappedValues, $now)
setInterimValue( $key, $value, $tempTTL, $newAsOf)
doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf=null)
Do the actual I/O for getWithSetCallback() when needed.
const HOLDOFF_NONE
Idiom for delete() for "no hold-off".
const COOLOFF_TTL
Seconds to no-op key set() calls to avoid large blob I/O stampedes.
getCheckKeyTime( $key)
Fetch the value of a timestamp "check" key.
const RECENT_SET_HIGH_MS
Max millisecond set() backoff for keys in hold-off (far less than INTERIM_KEY_TTL)
relayDelete( $key)
Do the actual async bus delete of a key.
const LOCK_TTL
Seconds to keep lock keys around.
getMultiWithUnionSetCallback(ArrayIterator $keyedIds, $ttl, callable $callback, array $opts=[])
Method to fetch/regenerate multiple cache keys at once.
static prefixCacheKeys(array $keys, $prefix)
getMultiWithSetCallback(ArrayIterator $keyedIds, $ttl, callable $callback, array $opts=[])
Method to fetch multiple cache keys at once with regeneration.
const HIT_RATE_HIGH
Hits/second for a refresh to be expected within the "popularity" window.
const INTERIM_KEY_TTL
Seconds to keep interim value keys for tombstoned keys around.
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
worthRefreshExpiring( $curTTL, $lowTTL)
Check if a key is nearing expiration and thus due for randomized regeneration.
getWithSetCallback( $key, $ttl, $callback, array $opts=[])
Method to fetch/regenerate cache keys.
makeMultiKeys(array $entities, callable $keyFunc)
bool $useInterimHoldOffCaching
Whether to use "interim" caching while keys are tombstoned.
const MAX_READ_LAG
Max replication+snapshot lag before applying TTL_LAGGED or disallowing set()
resolveTouched( $value, $lastPurge, $touchedCallback)
const CHECK_KEY_TTL
Seconds to keep dependency purge keys around.
const MIN_TIMESTAMP_NONE
Idiom for getWithSetCallback() for "no minimum required as-of timestamp".
useInterimHoldOffCaching( $enabled)
Enable or disable the use of brief caching for tombstoned keys.
const TINY_POSTIVE
Tiny positive float to use when using "minTime" to assert an inequality.
StatsdDataFactoryInterface $stats
clearProcessCache()
Clear the in-process caches; useful for testing.
string $region
Physical region for mcrouter use.
wrap( $value, $ttl, $now)
Do not use this method outside WANObjectCache.
float $epoch
Unix timestamp of the oldest possible valid values.
callable null $asyncHandler
Function that takes a WAN cache callback and runs it later.
const SET_DELAY_HIGH_MS
Milliseconds of delay after get() where set() storms are a consideration with 'lockTSE'.
reap( $key, $purgeTimestamp, &$isStale=false)
Set a key to soon expire in the local cluster if it pre-dates $purgeTimestamp.
makePurgeValue( $timestamp, $holdoff)
getRawKeysForWarmup(array $keys, array $checkKeys)
const RECENT_SET_LOW_MS
Min millisecond set() backoff for keys in hold-off (far less than INTERIM_KEY_TTL)
setLogger(LoggerInterface $logger)
reapCheckKey( $key, $purgeTimestamp, &$isStale=false)
Set a "check" key to soon expire in the local cluster if it pre-dates $purgeTimestamp.
const PASS_BY_REF
Parameter to get()/getMulti() to return extra information by reference.
makeKey( $class, $component=null)
clearLastError()
Clear the "last error" registry.
const STALE_TTL_NONE
Idiom for set()/getWithSetCallback() for "do not augment the storage medium TTL".
MapCacheLRU[] $processCaches
Map of group PHP instance caches.
const TSE_NONE
Idiom for getWithSetCallback() callbacks to 'lockTSE' logic.
resetCheckKey( $key)
Delete a "check" key from all datacenters, invalidating keys that use it.
makeGlobalKey( $class, $component=null)
const MAX_COMMIT_DELAY
Max time expected to pass between delete() and DB commit finishing.
const AGE_NEW
Never consider performing "popularity" refreshes until a key reaches this age.
const RAMPUP_TTL
Seconds to ramp up to the "popularity" refresh chance after a key is no longer new.
const TTL_LAGGED
Max TTL to store keys when a data sourced is lagged.
isAliveOrInGracePeriod( $curTTL, $graceTTL)
Check if a key is fresh or in the grace window and thus due for randomized reuse.
getMultiCheckKeyTime(array $keys)
Fetch the values of each timestamp "check" key.
$mcrouterAware
@bar bool Whether to use mcrouter key prefixing for routing
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
see documentation in includes Linker php for Linker::makeImageLink & $time
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
processing should stop and the error should be shown to the user * false
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Generic interface for lightweight expiring object stores.
you have access to all of the normal MediaWiki so you can get a DB use the cache
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))