MediaWiki REL1_29
WANObjectCache.php
Go to the documentation of this file.
1<?php
23use Psr\Log\LoggerAwareInterface;
24use Psr\Log\LoggerInterface;
25use Psr\Log\NullLogger;
26
81class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
83 protected $cache;
85 protected $processCaches = [];
87 protected $purgeChannel;
89 protected $purgeRelayer;
91 protected $logger;
92
94 protected $lastRelayError = self::ERR_NONE;
95
97 private $callbackDepth = 0;
99 private $warmupCache = [];
100
104 const MAX_READ_LAG = 7;
106 const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
107
109 const CHECK_KEY_TTL = self::TTL_YEAR;
111 const LOCK_TTL = 10;
113 const LOW_TTL = 30;
115 const LOCK_TSE = 1;
116
118 const AGE_NEW = 60;
120 const HOT_TTR = 900;
122 const HIT_RATE_HIGH = 1;
124 const RAMPUP_TTL = 30;
125
127 const TTL_UNCACHEABLE = -1;
129 const TSE_NONE = -1;
131 const TTL_LAGGED = 30;
133 const HOLDOFF_NONE = 0;
136
138 const TINY_NEGATIVE = -0.000001;
139
141 const VERSION = 1;
142
143 const FLD_VERSION = 0; // key to cache version number
144 const FLD_VALUE = 1; // key to the cached value
145 const FLD_TTL = 2; // key to the original TTL
146 const FLD_TIME = 3; // key to the cache time
147 const FLD_FLAGS = 4; // key to the flags bitfield
148 const FLD_HOLDOFF = 5; // key to any hold-off TTL
149
151 const FLG_STALE = 1;
152
153 const ERR_NONE = 0; // no error
154 const ERR_NO_RESPONSE = 1; // no response
155 const ERR_UNREACHABLE = 2; // can't connect
156 const ERR_UNEXPECTED = 3; // response gave some error
157 const ERR_RELAY = 4; // relay broadcast failed
158
159 const VALUE_KEY_PREFIX = 'WANCache:v:';
160 const INTERIM_KEY_PREFIX = 'WANCache:i:';
161 const TIME_KEY_PREFIX = 'WANCache:t:';
162 const MUTEX_KEY_PREFIX = 'WANCache:m:';
163
164 const PURGE_VAL_PREFIX = 'PURGED:';
165
166 const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
167 const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
168
169 const PC_PRIMARY = 'primary:1000'; // process cache name and max key count
170
171 const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
172
180 public function __construct( array $params ) {
181 $this->cache = $params['cache'];
182 $this->purgeChannel = isset( $params['channels']['purge'] )
183 ? $params['channels']['purge']
184 : self::DEFAULT_PURGE_CHANNEL;
185 $this->purgeRelayer = isset( $params['relayers']['purge'] )
186 ? $params['relayers']['purge']
187 : new EventRelayerNull( [] );
188 $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
189 }
190
191 public function setLogger( LoggerInterface $logger ) {
192 $this->logger = $logger;
193 }
194
200 public static function newEmpty() {
201 return new self( [
202 'cache' => new EmptyBagOStuff(),
203 'pool' => 'empty',
204 'relayer' => new EventRelayerNull( [] )
205 ] );
206 }
207
248 final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
249 $curTTLs = [];
250 $asOfs = [];
251 $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
252 $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
253 $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null;
254
255 return isset( $values[$key] ) ? $values[$key] : false;
256 }
257
270 final public function getMulti(
271 array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
272 ) {
273 $result = [];
274 $curTTLs = [];
275 $asOfs = [];
276
277 $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
278 $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
279
280 $checkKeysForAll = [];
281 $checkKeysByKey = [];
282 $checkKeysFlat = [];
283 foreach ( $checkKeys as $i => $checkKeyGroup ) {
284 $prefixed = self::prefixCacheKeys( (array)$checkKeyGroup, self::TIME_KEY_PREFIX );
285 $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
286 // Is this check keys for a specific cache key, or for all keys being fetched?
287 if ( is_int( $i ) ) {
288 $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
289 } else {
290 $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
291 ? array_merge( $checkKeysByKey[$i], $prefixed )
292 : $prefixed;
293 }
294 }
295
296 // Fetch all of the raw values
297 $keysGet = array_merge( $valueKeys, $checkKeysFlat );
298 if ( $this->warmupCache ) {
299 $wrappedValues = array_intersect_key( $this->warmupCache, array_flip( $keysGet ) );
300 $keysGet = array_diff( $keysGet, array_keys( $wrappedValues ) ); // keys left to fetch
301 } else {
302 $wrappedValues = [];
303 }
304 $wrappedValues += $this->cache->getMulti( $keysGet );
305 // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
306 $now = microtime( true );
307
308 // Collect timestamps from all "check" keys
309 $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
310 $purgeValuesByKey = [];
311 foreach ( $checkKeysByKey as $cacheKey => $checks ) {
312 $purgeValuesByKey[$cacheKey] =
313 $this->processCheckKeys( $checks, $wrappedValues, $now );
314 }
315
316 // Get the main cache value for each key and validate them
317 foreach ( $valueKeys as $vKey ) {
318 if ( !isset( $wrappedValues[$vKey] ) ) {
319 continue; // not found
320 }
321
322 $key = substr( $vKey, $vPrefixLen ); // unprefix
323
324 list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
325 if ( $value !== false ) {
326 $result[$key] = $value;
327
328 // Force dependant keys to be invalid for a while after purging
329 // to reduce race conditions involving stale data getting cached
330 $purgeValues = $purgeValuesForAll;
331 if ( isset( $purgeValuesByKey[$key] ) ) {
332 $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
333 }
334 foreach ( $purgeValues as $purge ) {
335 $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
336 if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
337 // How long ago this value was expired by *this* check key
338 $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
339 // How long ago this value was expired by *any* known check key
340 $curTTL = min( $curTTL, $ago );
341 }
342 }
343 }
344 $curTTLs[$key] = $curTTL;
345 $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
346 }
347
348 return $result;
349 }
350
358 private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
359 $purgeValues = [];
360 foreach ( $timeKeys as $timeKey ) {
361 $purge = isset( $wrappedValues[$timeKey] )
362 ? self::parsePurgeValue( $wrappedValues[$timeKey] )
363 : false;
364 if ( $purge === false ) {
365 // Key is not set or invalid; regenerate
366 $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
367 $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
368 $purge = self::parsePurgeValue( $newVal );
369 }
370 $purgeValues[] = $purge;
371 }
372 return $purgeValues;
373 }
374
433 final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
434 $now = microtime( true );
435 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
436 $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
437 $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
438 $staleTTL = isset( $opts['staleTTL'] ) ? $opts['staleTTL'] : 0;
439
440 // Do not cache potentially uncommitted data as it might get rolled back
441 if ( !empty( $opts['pending'] ) ) {
442 $this->logger->info( "Rejected set() for $key due to pending writes." );
443
444 return true; // no-op the write for being unsafe
445 }
446
447 $wrapExtra = []; // additional wrapped value fields
448 // Check if there's a risk of writing stale data after the purge tombstone expired
449 if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
450 // Case A: read lag with "lockTSE"; save but record value as stale
451 if ( $lockTSE >= 0 ) {
452 $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
453 $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
454 // Case B: any long-running transaction; ignore this set()
455 } elseif ( $age > self::MAX_READ_LAG ) {
456 $this->logger->info( "Rejected set() for $key due to snapshot lag." );
457
458 return true; // no-op the write for being unsafe
459 // Case C: high replication lag; lower TTL instead of ignoring all set()s
460 } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
461 $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
462 $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
463 // Case D: medium length request with medium replication lag; ignore this set()
464 } else {
465 $this->logger->info( "Rejected set() for $key due to high read lag." );
466
467 return true; // no-op the write for being unsafe
468 }
469 }
470
471 // Wrap that value with time/TTL/version metadata
472 $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
473
474 $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
475 return ( is_string( $cWrapped ) )
476 ? false // key is tombstoned; do nothing
477 : $wrapped;
478 };
479
480 return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl + $staleTTL, 1 );
481 }
482
540 final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
541 $key = self::VALUE_KEY_PREFIX . $key;
542
543 if ( $ttl <= 0 ) {
544 // Publish the purge to all datacenters
545 $ok = $this->relayDelete( $key );
546 } else {
547 // Publish the purge to all datacenters
548 $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE );
549 }
550
551 return $ok;
552 }
553
573 final public function getCheckKeyTime( $key ) {
574 $key = self::TIME_KEY_PREFIX . $key;
575
576 $purge = self::parsePurgeValue( $this->cache->get( $key ) );
577 if ( $purge !== false ) {
578 $time = $purge[self::FLD_TIME];
579 } else {
580 // Casting assures identical floats for the next getCheckKeyTime() calls
581 $now = (string)microtime( true );
582 $this->cache->add( $key,
583 $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
584 self::CHECK_KEY_TTL
585 );
586 $time = (float)$now;
587 }
588
589 return $time;
590 }
591
625 final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
626 // Publish the purge to all datacenters
627 return $this->relayPurge( self::TIME_KEY_PREFIX . $key, self::CHECK_KEY_TTL, $holdoff );
628 }
629
660 final public function resetCheckKey( $key ) {
661 // Publish the purge to all datacenters
662 return $this->relayDelete( self::TIME_KEY_PREFIX . $key );
663 }
664
854 final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
855 $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
856
857 // Try the process cache if enabled and the cache callback is not within a cache callback.
858 // Process cache use in nested callbacks is not lag-safe with regard to HOLDOFF_TTL since
859 // the in-memory value is further lagged than the shared one since it uses a blind TTL.
860 if ( $pcTTL >= 0 && $this->callbackDepth == 0 ) {
861 $group = isset( $opts['pcGroup'] ) ? $opts['pcGroup'] : self::PC_PRIMARY;
862 $procCache = $this->getProcessCache( $group );
863 $value = $procCache->get( $key );
864 } else {
865 $procCache = false;
866 $value = false;
867 }
868
869 if ( $value === false ) {
870 // Fetch the value over the network
871 if ( isset( $opts['version'] ) ) {
872 $version = $opts['version'];
873 $asOf = null;
874 $cur = $this->doGetWithSetCallback(
875 $key,
876 $ttl,
877 function ( $oldValue, &$ttl, &$setOpts, $oldAsOf )
878 use ( $callback, $version ) {
879 if ( is_array( $oldValue )
880 && array_key_exists( self::VFLD_DATA, $oldValue )
881 ) {
882 $oldData = $oldValue[self::VFLD_DATA];
883 } else {
884 // VFLD_DATA is not set if an old, unversioned, key is present
885 $oldData = false;
886 }
887
888 return [
889 self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts, $oldAsOf ),
890 self::VFLD_VERSION => $version
891 ];
892 },
893 $opts,
894 $asOf
895 );
896 if ( $cur[self::VFLD_VERSION] === $version ) {
897 // Value created or existed before with version; use it
898 $value = $cur[self::VFLD_DATA];
899 } else {
900 // Value existed before with a different version; use variant key.
901 // Reflect purges to $key by requiring that this key value be newer.
903 'cache-variant:' . md5( $key ) . ":$version",
904 $ttl,
905 $callback,
906 // Regenerate value if not newer than $key
907 [ 'version' => null, 'minAsOf' => $asOf ] + $opts
908 );
909 }
910 } else {
911 $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
912 }
913
914 // Update the process cache if enabled
915 if ( $procCache && $value !== false ) {
916 $procCache->set( $key, $value, $pcTTL );
917 }
918 }
919
920 return $value;
921 }
922
936 protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
937 $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
938 $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
939 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
940 $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
941 $popWindow = isset( $opts['hotTTR'] ) ? $opts['hotTTR'] : self::HOT_TTR;
942 $ageNew = isset( $opts['ageNew'] ) ? $opts['ageNew'] : self::AGE_NEW;
943 $minTime = isset( $opts['minAsOf'] ) ? $opts['minAsOf'] : self::MIN_TIMESTAMP_NONE;
944 $versioned = isset( $opts['version'] );
945
946 // Get the current key value
947 $curTTL = null;
948 $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
949 $value = $cValue; // return value
950
951 $preCallbackTime = microtime( true );
952 // Determine if a cached value regeneration is needed or desired
953 if ( $value !== false
954 && $curTTL > 0
955 && $this->isValid( $value, $versioned, $asOf, $minTime )
956 && !$this->worthRefreshExpiring( $curTTL, $lowTTL )
957 && !$this->worthRefreshPopular( $asOf, $ageNew, $popWindow, $preCallbackTime )
958 ) {
959 return $value;
960 }
961
962 // A deleted key with a negative TTL left must be tombstoned
963 $isTombstone = ( $curTTL !== null && $value === false );
964 // Assume a key is hot if requested soon after invalidation
965 $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
966 // Use the mutex if there is no value and a busy fallback is given
967 $checkBusy = ( $busyValue !== null && $value === false );
968 // Decide whether a single thread should handle regenerations.
969 // This avoids stampedes when $checkKeys are bumped and when preemptive
970 // renegerations take too long. It also reduces regenerations while $key
971 // is tombstoned. This balances cache freshness with avoiding DB load.
972 $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
973
974 $lockAcquired = false;
975 if ( $useMutex ) {
976 // Acquire a datacenter-local non-blocking lock
977 if ( $this->cache->add( self::MUTEX_KEY_PREFIX . $key, 1, self::LOCK_TTL ) ) {
978 // Lock acquired; this thread should update the key
979 $lockAcquired = true;
980 } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
981 // If it cannot be acquired; then the stale value can be used
982 return $value;
983 } else {
984 // Use the INTERIM value for tombstoned keys to reduce regeneration load.
985 // For hot keys, either another thread has the lock or the lock failed;
986 // use the INTERIM value from the last thread that regenerated it.
987 $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
988 list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
989 if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
990 $asOf = $wrapped[self::FLD_TIME];
991
992 return $value;
993 }
994 // Use the busy fallback value if nothing else
995 if ( $busyValue !== null ) {
996 return is_callable( $busyValue ) ? $busyValue() : $busyValue;
997 }
998 }
999 }
1000
1001 if ( !is_callable( $callback ) ) {
1002 throw new InvalidArgumentException( "Invalid cache miss callback provided." );
1003 }
1004
1005 // Generate the new value from the callback...
1006 $setOpts = [];
1007 ++$this->callbackDepth;
1008 try {
1009 $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts, $asOf ] );
1010 } finally {
1011 --$this->callbackDepth;
1012 }
1013 // When delete() is called, writes are write-holed by the tombstone,
1014 // so use a special INTERIM key to pass the new value around threads.
1015 if ( ( $isTombstone && $lockTSE > 0 ) && $value !== false && $ttl >= 0 ) {
1016 $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
1017 $newAsOf = microtime( true );
1018 $wrapped = $this->wrap( $value, $tempTTL, $newAsOf );
1019 // Avoid using set() to avoid pointless mcrouter broadcasting
1020 $this->cache->merge(
1021 self::INTERIM_KEY_PREFIX . $key,
1022 function () use ( $wrapped ) {
1023 return $wrapped;
1024 },
1025 $tempTTL,
1026 1
1027 );
1028 }
1029
1030 if ( $value !== false && $ttl >= 0 ) {
1031 $setOpts['lockTSE'] = $lockTSE;
1032 // Use best known "since" timestamp if not provided
1033 $setOpts += [ 'since' => $preCallbackTime ];
1034 // Update the cache; this will fail if the key is tombstoned
1035 $this->set( $key, $value, $ttl, $setOpts );
1036 }
1037
1038 if ( $lockAcquired ) {
1039 // Avoid using delete() to avoid pointless mcrouter broadcasting
1040 $this->cache->changeTTL( self::MUTEX_KEY_PREFIX . $key, 1 );
1041 }
1042
1043 return $value;
1044 }
1045
1103 final public function getMultiWithSetCallback(
1104 ArrayIterator $keyedIds, $ttl, callable $callback, array $opts = []
1105 ) {
1106 $keysWarmUp = iterator_to_array( $keyedIds, true );
1107 $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
1108 foreach ( $checkKeys as $i => $checkKeyOrKeys ) {
1109 if ( is_int( $i ) ) {
1110 $keysWarmUp[] = $checkKeyOrKeys;
1111 } else {
1112 $keysWarmUp = array_merge( $keysWarmUp, $checkKeyOrKeys );
1113 }
1114 }
1115
1116 $this->warmupCache = $this->cache->getMulti( $keysWarmUp );
1117 $this->warmupCache += array_fill_keys( $keysWarmUp, false );
1118
1119 // Wrap $callback to match the getWithSetCallback() format while passing $id to $callback
1120 $id = null;
1121 $func = function ( $oldValue, &$ttl, array $setOpts, $oldAsOf ) use ( $callback, &$id ) {
1122 return $callback( $id, $oldValue, $ttl, $setOpts, $oldAsOf );
1123 };
1124
1125 $values = [];
1126 foreach ( $keyedIds as $key => $id ) {
1127 $values[$key] = $this->getWithSetCallback( $key, $ttl, $func, $opts );
1128 }
1129
1130 $this->warmupCache = [];
1131
1132 return $values;
1133 }
1134
1147 public function reap( $key, $purgeTimestamp, &$isStale = false ) {
1148 $minAsOf = $purgeTimestamp + self::HOLDOFF_TTL;
1149 $wrapped = $this->cache->get( self::VALUE_KEY_PREFIX . $key );
1150 if ( is_array( $wrapped ) && $wrapped[self::FLD_TIME] < $minAsOf ) {
1151 $isStale = true;
1152 $this->logger->warning( "Reaping stale value key '$key'." );
1153 $ttlReap = self::HOLDOFF_TTL; // avoids races with tombstone creation
1154 $ok = $this->cache->changeTTL( self::VALUE_KEY_PREFIX . $key, $ttlReap );
1155 if ( !$ok ) {
1156 $this->logger->error( "Could not complete reap of key '$key'." );
1157 }
1158
1159 return $ok;
1160 }
1161
1162 $isStale = false;
1163
1164 return true;
1165 }
1166
1176 public function reapCheckKey( $key, $purgeTimestamp, &$isStale = false ) {
1177 $purge = $this->parsePurgeValue( $this->cache->get( self::TIME_KEY_PREFIX . $key ) );
1178 if ( $purge && $purge[self::FLD_TIME] < $purgeTimestamp ) {
1179 $isStale = true;
1180 $this->logger->warning( "Reaping stale check key '$key'." );
1181 $ok = $this->cache->changeTTL( self::TIME_KEY_PREFIX . $key, 1 );
1182 if ( !$ok ) {
1183 $this->logger->error( "Could not complete reap of check key '$key'." );
1184 }
1185
1186 return $ok;
1187 }
1188
1189 $isStale = false;
1190
1191 return false;
1192 }
1193
1200 public function makeKey() {
1201 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1202 }
1203
1210 public function makeGlobalKey() {
1211 return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
1212 }
1213
1220 public function makeMultiKeys( array $entities, callable $keyFunc ) {
1221 $map = [];
1222 foreach ( $entities as $entity ) {
1223 $map[$keyFunc( $entity, $this )] = $entity;
1224 }
1225
1226 return new ArrayIterator( $map );
1227 }
1228
1233 final public function getLastError() {
1234 if ( $this->lastRelayError ) {
1235 // If the cache and the relayer failed, focus on the latter.
1236 // An update not making it to the relayer means it won't show up
1237 // in other DCs (nor will consistent re-hashing see up-to-date values).
1238 // On the other hand, if just the cache update failed, then it should
1239 // eventually be applied by the relayer.
1240 return $this->lastRelayError;
1241 }
1242
1243 $code = $this->cache->getLastError();
1244 switch ( $code ) {
1245 case BagOStuff::ERR_NONE:
1246 return self::ERR_NONE;
1247 case BagOStuff::ERR_NO_RESPONSE:
1248 return self::ERR_NO_RESPONSE;
1249 case BagOStuff::ERR_UNREACHABLE:
1250 return self::ERR_UNREACHABLE;
1251 default:
1252 return self::ERR_UNEXPECTED;
1253 }
1254 }
1255
1259 final public function clearLastError() {
1260 $this->cache->clearLastError();
1261 $this->lastRelayError = self::ERR_NONE;
1262 }
1263
1269 public function clearProcessCache() {
1270 $this->processCaches = [];
1271 }
1272
1278 public function getQoS( $flag ) {
1279 return $this->cache->getQoS( $flag );
1280 }
1281
1305 public function adaptiveTTL( $mtime, $maxTTL, $minTTL = 30, $factor = .2 ) {
1306 if ( is_float( $mtime ) || ctype_digit( $mtime ) ) {
1307 $mtime = (int)$mtime; // handle fractional seconds and string integers
1308 }
1309
1310 if ( !is_int( $mtime ) || $mtime <= 0 ) {
1311 return $minTTL; // no last-modified time provided
1312 }
1313
1314 $age = time() - $mtime;
1315
1316 return (int)min( $maxTTL, max( $minTTL, $factor * $age ) );
1317 }
1318
1329 protected function relayPurge( $key, $ttl, $holdoff ) {
1330 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1331 // This handles the mcrouter and the single-DC case
1332 $ok = $this->cache->set( $key,
1333 $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
1334 $ttl
1335 );
1336 } else {
1337 $event = $this->cache->modifySimpleRelayEvent( [
1338 'cmd' => 'set',
1339 'key' => $key,
1340 'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1341 'ttl' => max( $ttl, 1 ),
1342 'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1343 ] );
1344
1345 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1346 if ( !$ok ) {
1347 $this->lastRelayError = self::ERR_RELAY;
1348 }
1349 }
1350
1351 return $ok;
1352 }
1353
1360 protected function relayDelete( $key ) {
1361 if ( $this->purgeRelayer instanceof EventRelayerNull ) {
1362 // This handles the mcrouter and the single-DC case
1363 $ok = $this->cache->delete( $key );
1364 } else {
1365 $event = $this->cache->modifySimpleRelayEvent( [
1366 'cmd' => 'delete',
1367 'key' => $key,
1368 ] );
1369
1370 $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1371 if ( !$ok ) {
1372 $this->lastRelayError = self::ERR_RELAY;
1373 }
1374 }
1375
1376 return $ok;
1377 }
1378
1391 protected function worthRefreshExpiring( $curTTL, $lowTTL ) {
1392 if ( $curTTL >= $lowTTL ) {
1393 return false;
1394 } elseif ( $curTTL <= 0 ) {
1395 return true;
1396 }
1397
1398 $chance = ( 1 - $curTTL / $lowTTL );
1399
1400 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1401 }
1402
1418 protected function worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now ) {
1419 $age = $now - $asOf;
1420 $timeOld = $age - $ageNew;
1421 if ( $timeOld <= 0 ) {
1422 return false;
1423 }
1424
1425 // Lifecycle is: new, ramp-up refresh chance, full refresh chance.
1426 // Note that the "expected # of refreshes" for the ramp-up time range is half of what it
1427 // would be if P(refresh) was at its full value during that time range.
1428 $refreshWindowSec = max( $timeTillRefresh - $ageNew - self::RAMPUP_TTL / 2, 1 );
1429 // P(refresh) * (# hits in $refreshWindowSec) = (expected # of refreshes)
1430 // P(refresh) * ($refreshWindowSec * $popularHitsPerSec) = 1
1431 // P(refresh) = 1/($refreshWindowSec * $popularHitsPerSec)
1432 $chance = 1 / ( self::HIT_RATE_HIGH * $refreshWindowSec );
1433
1434 // Ramp up $chance from 0 to its nominal value over RAMPUP_TTL seconds to avoid stampedes
1435 $chance *= ( $timeOld <= self::RAMPUP_TTL ) ? $timeOld / self::RAMPUP_TTL : 1;
1436
1437 return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1438 }
1439
1449 protected function isValid( $value, $versioned, $asOf, $minTime ) {
1450 if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1451 return false;
1452 } elseif ( $minTime > 0 && $asOf < $minTime ) {
1453 return false;
1454 }
1455
1456 return true;
1457 }
1458
1467 protected function wrap( $value, $ttl, $now ) {
1468 return [
1469 self::FLD_VERSION => self::VERSION,
1470 self::FLD_VALUE => $value,
1471 self::FLD_TTL => $ttl,
1472 self::FLD_TIME => $now
1473 ];
1474 }
1475
1483 protected function unwrap( $wrapped, $now ) {
1484 // Check if the value is a tombstone
1485 $purge = self::parsePurgeValue( $wrapped );
1486 if ( $purge !== false ) {
1487 // Purged values should always have a negative current $ttl
1488 $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1489 return [ false, $curTTL ];
1490 }
1491
1492 if ( !is_array( $wrapped ) // not found
1493 || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1494 || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1495 ) {
1496 return [ false, null ];
1497 }
1498
1499 $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1500 if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1501 // Treat as expired, with the cache time as the expiration
1502 $age = $now - $wrapped[self::FLD_TIME];
1503 $curTTL = min( -$age, self::TINY_NEGATIVE );
1504 } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1505 // Get the approximate time left on the key
1506 $age = $now - $wrapped[self::FLD_TIME];
1507 $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1508 } else {
1509 // Key had no TTL, so the time left is unbounded
1510 $curTTL = INF;
1511 }
1512
1513 return [ $wrapped[self::FLD_VALUE], $curTTL ];
1514 }
1515
1521 protected static function prefixCacheKeys( array $keys, $prefix ) {
1522 $res = [];
1523 foreach ( $keys as $key ) {
1524 $res[] = $prefix . $key;
1525 }
1526
1527 return $res;
1528 }
1529
1535 protected static function parsePurgeValue( $value ) {
1536 if ( !is_string( $value ) ) {
1537 return false;
1538 }
1539 $segments = explode( ':', $value, 3 );
1540 if ( !isset( $segments[0] ) || !isset( $segments[1] )
1541 || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1542 ) {
1543 return false;
1544 }
1545 if ( !isset( $segments[2] ) ) {
1546 // Back-compat with old purge values without holdoff
1547 $segments[2] = self::HOLDOFF_TTL;
1548 }
1549 return [
1550 self::FLD_TIME => (float)$segments[1],
1551 self::FLD_HOLDOFF => (int)$segments[2],
1552 ];
1553 }
1554
1560 protected function makePurgeValue( $timestamp, $holdoff ) {
1561 return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1562 }
1563
1568 protected function getProcessCache( $group ) {
1569 if ( !isset( $this->processCaches[$group] ) ) {
1570 list( , $n ) = explode( ':', $group );
1571 $this->processCaches[$group] = new HashBagOStuff( [ 'maxKeys' => (int)$n ] );
1572 }
1573
1574 return $this->processCaches[$group];
1575 }
1576}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
interface is intended to be more or less compatible with the PHP memcached client.
Definition BagOStuff.php:47
A BagOStuff object with no objects in it.
No-op class for publishing messages into a PubSub system.
Base class for reliable event relays.
Simple store for keeping values in an associative array for the current process.
Multi-datacenter aware caching interface.
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)
unwrap( $wrapped, $now)
Do not use this method outside WANObjectCache.
worthRefreshPopular( $asOf, $ageNew, $timeTillRefresh, $now)
Check if a key is due for randomized regeneration due to its popularity.
adaptiveTTL( $mtime, $maxTTL, $minTTL=30, $factor=.2)
Get a TTL that is higher for objects that have not changed recently.
touchCheckKey( $key, $holdoff=self::HOLDOFF_TTL)
Purge a "check" key from all datacenters, invalidating keys that use it.
const LOCK_TSE
Default time-since-expiry on a miss that makes a key "hot".
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.
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.
isValid( $value, $versioned, $asOf, $minTime)
Check whether $value is appropriately versioned and not older than $minTime (if set)
processCheckKeys(array $timeKeys, array $wrappedValues, $now)
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".
getMulti(array $keys, &$curTTLs=[], array $checkKeys=[], array &$asOfs=[])
Fetch the value of several keys from cache.
getCheckKeyTime( $key)
Fetch the value of a timestamp "check" key.
HashBagOStuff[] $processCaches
Map of group PHP instance caches.
relayDelete( $key)
Do the actual async bus delete of a key.
static parsePurgeValue( $value)
const LOCK_TTL
Seconds to keep lock keys around.
LoggerInterface $logger
static prefixCacheKeys(array $keys, $prefix)
getMultiWithSetCallback(ArrayIterator $keyedIds, $ttl, callable $callback, array $opts=[])
Method to fetch/regenerate multiple cache keys at once.
const HIT_RATE_HIGH
Hits/second for a refresh to be expected within the "popularity" window.
EventRelayer $purgeRelayer
Bus that handles purge broadcasts.
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
worthRefreshExpiring( $curTTL, $lowTTL)
Check if a key should be regenerated (using random probability)
getWithSetCallback( $key, $ttl, $callback, array $opts=[])
Method to fetch/regenerate cache keys.
makeMultiKeys(array $entities, callable $keyFunc)
const MAX_READ_LAG
Max replication+snapshot lag before applying TTL_LAGGED or disallowing set()
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".
clearProcessCache()
Clear the in-process caches; useful for testing.
wrap( $value, $ttl, $now)
Do not use this method outside WANObjectCache.
int $lastRelayError
ERR_* constant for the "last error" registry.
string $purgeChannel
Purge channel name.
reap( $key, $purgeTimestamp, &$isStale=false)
Locally set a key to expire soon if it is stale based on $purgeTimestamp.
makePurgeValue( $timestamp, $holdoff)
setLogger(LoggerInterface $logger)
reapCheckKey( $key, $purgeTimestamp, &$isStale=false)
Locally set a "check" key to expire soon if it is stale based on $purgeTimestamp.
integer $callbackDepth
Callback stack depth for getWithSetCallback()
clearLastError()
Clear the "last error" registry.
const TSE_NONE
Idiom for getWithSetCallback() callbacks to 'lockTSE' logic.
resetCheckKey( $key)
Delete a "check" key from all datacenters, invalidating keys that use it.
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.
$res
Definition database.txt:21
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
Definition deferred.txt:11
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
the array() calling protocol came about after MediaWiki 1.4rc1.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1769
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. '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 '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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
Definition hooks.txt:1954
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
Definition hooks.txt:183
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub 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
Definition hooks.txt:865
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition hooks.txt:2753
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
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
Definition injection.txt:37
Generic base class for storage interfaces.
you have access to all of the normal MediaWiki so you can get a DB use the cache
$cache
Definition mcc.php:33
$params