MediaWiki  master
WANObjectCache.php
Go to the documentation of this file.
1 <?php
23 use Psr\Log\LoggerAwareInterface;
24 use Psr\Log\LoggerInterface;
25 use Psr\Log\NullLogger;
26 
67 class WANObjectCache implements IExpiringStore, LoggerAwareInterface {
69  protected $cache;
71  protected $procCache;
73  protected $purgeChannel;
75  protected $purgeRelayer;
77  protected $logger;
78 
80  protected $lastRelayError = self::ERR_NONE;
81 
83  const MAX_COMMIT_DELAY = 3;
85  const MAX_READ_LAG = 7;
87  const HOLDOFF_TTL = 11; // MAX_COMMIT_DELAY + MAX_READ_LAG + 1
88 
90  const CHECK_KEY_TTL = self::TTL_YEAR;
92  const LOCK_TTL = 10;
94  const LOW_TTL = 30;
96  const LOCK_TSE = 1;
97 
99  const TTL_UNCACHEABLE = -1;
101  const TSE_NONE = -1;
103  const TTL_LAGGED = 30;
105  const HOLDOFF_NONE = 0;
106 
108  const TINY_NEGATIVE = -0.000001;
109 
111  const VERSION = 1;
112 
113  const FLD_VERSION = 0; // key to cache version number
114  const FLD_VALUE = 1; // key to the cached value
115  const FLD_TTL = 2; // key to the original TTL
116  const FLD_TIME = 3; // key to the cache time
117  const FLD_FLAGS = 4; // key to the flags bitfield
118  const FLD_HOLDOFF = 5; // key to any hold-off TTL
119 
121  const FLG_STALE = 1;
122 
123  const ERR_NONE = 0; // no error
124  const ERR_NO_RESPONSE = 1; // no response
125  const ERR_UNREACHABLE = 2; // can't connect
126  const ERR_UNEXPECTED = 3; // response gave some error
127  const ERR_RELAY = 4; // relay broadcast failed
128 
129  const VALUE_KEY_PREFIX = 'WANCache:v:';
130  const INTERIM_KEY_PREFIX = 'WANCache:i:';
131  const TIME_KEY_PREFIX = 'WANCache:t:';
132 
133  const PURGE_VAL_PREFIX = 'PURGED:';
134 
135  const VFLD_DATA = 'WOC:d'; // key to the value of versioned data
136  const VFLD_VERSION = 'WOC:v'; // key to the version of the value present
137 
138  const MAX_PC_KEYS = 1000; // max keys to keep in process cache
139 
140  const DEFAULT_PURGE_CHANNEL = 'wancache-purge';
141 
149  public function __construct( array $params ) {
150  $this->cache = $params['cache'];
151  $this->procCache = new HashBagOStuff( [ 'maxKeys' => self::MAX_PC_KEYS ] );
152  $this->purgeChannel = isset( $params['channels']['purge'] )
153  ? $params['channels']['purge']
154  : self::DEFAULT_PURGE_CHANNEL;
155  $this->purgeRelayer = isset( $params['relayers']['purge'] )
156  ? $params['relayers']['purge']
157  : new EventRelayerNull( [] );
158  $this->setLogger( isset( $params['logger'] ) ? $params['logger'] : new NullLogger() );
159  }
160 
161  public function setLogger( LoggerInterface $logger ) {
162  $this->logger = $logger;
163  }
164 
170  public static function newEmpty() {
171  return new self( [
172  'cache' => new EmptyBagOStuff(),
173  'pool' => 'empty',
174  'relayer' => new EventRelayerNull( [] )
175  ] );
176  }
177 
218  final public function get( $key, &$curTTL = null, array $checkKeys = [], &$asOf = null ) {
219  $curTTLs = [];
220  $asOfs = [];
221  $values = $this->getMulti( [ $key ], $curTTLs, $checkKeys, $asOfs );
222  $curTTL = isset( $curTTLs[$key] ) ? $curTTLs[$key] : null;
223  $asOf = isset( $asOfs[$key] ) ? $asOfs[$key] : null;
224 
225  return isset( $values[$key] ) ? $values[$key] : false;
226  }
227 
240  final public function getMulti(
241  array $keys, &$curTTLs = [], array $checkKeys = [], array &$asOfs = []
242  ) {
243  $result = [];
244  $curTTLs = [];
245  $asOfs = [];
246 
247  $vPrefixLen = strlen( self::VALUE_KEY_PREFIX );
248  $valueKeys = self::prefixCacheKeys( $keys, self::VALUE_KEY_PREFIX );
249 
250  $checkKeysForAll = [];
251  $checkKeysByKey = [];
252  $checkKeysFlat = [];
253  foreach ( $checkKeys as $i => $keys ) {
254  $prefixed = self::prefixCacheKeys( (array)$keys, self::TIME_KEY_PREFIX );
255  $checkKeysFlat = array_merge( $checkKeysFlat, $prefixed );
256  // Is this check keys for a specific cache key, or for all keys being fetched?
257  if ( is_int( $i ) ) {
258  $checkKeysForAll = array_merge( $checkKeysForAll, $prefixed );
259  } else {
260  $checkKeysByKey[$i] = isset( $checkKeysByKey[$i] )
261  ? array_merge( $checkKeysByKey[$i], $prefixed )
262  : $prefixed;
263  }
264  }
265 
266  // Fetch all of the raw values
267  $wrappedValues = $this->cache->getMulti( array_merge( $valueKeys, $checkKeysFlat ) );
268  // Time used to compare/init "check" keys (derived after getMulti() to be pessimistic)
269  $now = microtime( true );
270 
271  // Collect timestamps from all "check" keys
272  $purgeValuesForAll = $this->processCheckKeys( $checkKeysForAll, $wrappedValues, $now );
273  $purgeValuesByKey = [];
274  foreach ( $checkKeysByKey as $cacheKey => $checks ) {
275  $purgeValuesByKey[$cacheKey] =
276  $this->processCheckKeys( $checks, $wrappedValues, $now );
277  }
278 
279  // Get the main cache value for each key and validate them
280  foreach ( $valueKeys as $vKey ) {
281  if ( !isset( $wrappedValues[$vKey] ) ) {
282  continue; // not found
283  }
284 
285  $key = substr( $vKey, $vPrefixLen ); // unprefix
286 
287  list( $value, $curTTL ) = $this->unwrap( $wrappedValues[$vKey], $now );
288  if ( $value !== false ) {
289  $result[$key] = $value;
290 
291  // Force dependant keys to be invalid for a while after purging
292  // to reduce race conditions involving stale data getting cached
293  $purgeValues = $purgeValuesForAll;
294  if ( isset( $purgeValuesByKey[$key] ) ) {
295  $purgeValues = array_merge( $purgeValues, $purgeValuesByKey[$key] );
296  }
297  foreach ( $purgeValues as $purge ) {
298  $safeTimestamp = $purge[self::FLD_TIME] + $purge[self::FLD_HOLDOFF];
299  if ( $safeTimestamp >= $wrappedValues[$vKey][self::FLD_TIME] ) {
300  // How long ago this value was expired by *this* check key
301  $ago = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
302  // How long ago this value was expired by *any* known check key
303  $curTTL = min( $curTTL, $ago );
304  }
305  }
306  }
307  $curTTLs[$key] = $curTTL;
308  $asOfs[$key] = ( $value !== false ) ? $wrappedValues[$vKey][self::FLD_TIME] : null;
309  }
310 
311  return $result;
312  }
313 
321  private function processCheckKeys( array $timeKeys, array $wrappedValues, $now ) {
322  $purgeValues = [];
323  foreach ( $timeKeys as $timeKey ) {
324  $purge = isset( $wrappedValues[$timeKey] )
325  ? self::parsePurgeValue( $wrappedValues[$timeKey] )
326  : false;
327  if ( $purge === false ) {
328  // Key is not set or invalid; regenerate
329  $newVal = $this->makePurgeValue( $now, self::HOLDOFF_TTL );
330  $this->cache->add( $timeKey, $newVal, self::CHECK_KEY_TTL );
331  $purge = self::parsePurgeValue( $newVal );
332  }
333  $purgeValues[] = $purge;
334  }
335  return $purgeValues;
336  }
337 
388  final public function set( $key, $value, $ttl = 0, array $opts = [] ) {
389  $now = microtime( true );
390  $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
391  $age = isset( $opts['since'] ) ? max( 0, $now - $opts['since'] ) : 0;
392  $lag = isset( $opts['lag'] ) ? $opts['lag'] : 0;
393 
394  // Do not cache potentially uncommitted data as it might get rolled back
395  if ( !empty( $opts['pending'] ) ) {
396  $this->logger->info( "Rejected set() for $key due to pending writes." );
397 
398  return true; // no-op the write for being unsafe
399  }
400 
401  $wrapExtra = []; // additional wrapped value fields
402  // Check if there's a risk of writing stale data after the purge tombstone expired
403  if ( $lag === false || ( $lag + $age ) > self::MAX_READ_LAG ) {
404  // Case A: read lag with "lockTSE"; save but record value as stale
405  if ( $lockTSE >= 0 ) {
406  $ttl = max( 1, (int)$lockTSE ); // set() expects seconds
407  $wrapExtra[self::FLD_FLAGS] = self::FLG_STALE; // mark as stale
408  // Case B: any long-running transaction; ignore this set()
409  } elseif ( $age > self::MAX_READ_LAG ) {
410  $this->logger->warning( "Rejected set() for $key due to snapshot lag." );
411 
412  return true; // no-op the write for being unsafe
413  // Case C: high replication lag; lower TTL instead of ignoring all set()s
414  } elseif ( $lag === false || $lag > self::MAX_READ_LAG ) {
415  $ttl = $ttl ? min( $ttl, self::TTL_LAGGED ) : self::TTL_LAGGED;
416  $this->logger->warning( "Lowered set() TTL for $key due to replication lag." );
417  // Case D: medium length request with medium replication lag; ignore this set()
418  } else {
419  $this->logger->warning( "Rejected set() for $key due to high read lag." );
420 
421  return true; // no-op the write for being unsafe
422  }
423  }
424 
425  // Wrap that value with time/TTL/version metadata
426  $wrapped = $this->wrap( $value, $ttl, $now ) + $wrapExtra;
427 
428  $func = function ( $cache, $key, $cWrapped ) use ( $wrapped ) {
429  return ( is_string( $cWrapped ) )
430  ? false // key is tombstoned; do nothing
431  : $wrapped;
432  };
433 
434  return $this->cache->merge( self::VALUE_KEY_PREFIX . $key, $func, $ttl, 1 );
435  }
436 
494  final public function delete( $key, $ttl = self::HOLDOFF_TTL ) {
495  $key = self::VALUE_KEY_PREFIX . $key;
496 
497  if ( $ttl <= 0 ) {
498  // Update the local datacenter immediately
499  $ok = $this->cache->delete( $key );
500  // Publish the purge to all datacenters
501  $ok = $this->relayDelete( $key ) && $ok;
502  } else {
503  // Update the local datacenter immediately
504  $ok = $this->cache->set( $key,
505  $this->makePurgeValue( microtime( true ), self::HOLDOFF_NONE ),
506  $ttl
507  );
508  // Publish the purge to all datacenters
509  $ok = $this->relayPurge( $key, $ttl, self::HOLDOFF_NONE ) && $ok;
510  }
511 
512  return $ok;
513  }
514 
534  final public function getCheckKeyTime( $key ) {
535  $key = self::TIME_KEY_PREFIX . $key;
536 
537  $purge = self::parsePurgeValue( $this->cache->get( $key ) );
538  if ( $purge !== false ) {
539  $time = $purge[self::FLD_TIME];
540  } else {
541  // Casting assures identical floats for the next getCheckKeyTime() calls
542  $now = (string)microtime( true );
543  $this->cache->add( $key,
544  $this->makePurgeValue( $now, self::HOLDOFF_TTL ),
545  self::CHECK_KEY_TTL
546  );
547  $time = (float)$now;
548  }
549 
550  return $time;
551  }
552 
584  final public function touchCheckKey( $key, $holdoff = self::HOLDOFF_TTL ) {
585  $key = self::TIME_KEY_PREFIX . $key;
586  // Update the local datacenter immediately
587  $ok = $this->cache->set( $key,
588  $this->makePurgeValue( microtime( true ), $holdoff ),
589  self::CHECK_KEY_TTL
590  );
591  // Publish the purge to all datacenters
592  return $this->relayPurge( $key, self::CHECK_KEY_TTL, $holdoff ) && $ok;
593  }
594 
622  final public function resetCheckKey( $key ) {
623  $key = self::TIME_KEY_PREFIX . $key;
624  // Update the local datacenter immediately
625  $ok = $this->cache->delete( $key );
626  // Publish the purge to all datacenters
627  return $this->relayDelete( $key ) && $ok;
628  }
629 
793  final public function getWithSetCallback( $key, $ttl, $callback, array $opts = [] ) {
794  $pcTTL = isset( $opts['pcTTL'] ) ? $opts['pcTTL'] : self::TTL_UNCACHEABLE;
795 
796  // Try the process cache if enabled
797  $value = ( $pcTTL >= 0 ) ? $this->procCache->get( $key ) : false;
798 
799  if ( $value === false ) {
800  unset( $opts['minTime'] ); // not a public feature
801 
802  // Fetch the value over the network
803  if ( isset( $opts['version'] ) ) {
804  $version = $opts['version'];
805  $asOf = null;
806  $cur = $this->doGetWithSetCallback(
807  $key,
808  $ttl,
809  function ( $oldValue, &$ttl, &$setOpts ) use ( $callback, $version ) {
810  if ( is_array( $oldValue )
811  && array_key_exists( self::VFLD_DATA, $oldValue )
812  ) {
813  $oldData = $oldValue[self::VFLD_DATA];
814  } else {
815  // VFLD_DATA is not set if an old, unversioned, key is present
816  $oldData = false;
817  }
818 
819  return [
820  self::VFLD_DATA => $callback( $oldData, $ttl, $setOpts ),
821  self::VFLD_VERSION => $version
822  ];
823  },
824  $opts,
825  $asOf
826  );
827  if ( $cur[self::VFLD_VERSION] === $version ) {
828  // Value created or existed before with version; use it
829  $value = $cur[self::VFLD_DATA];
830  } else {
831  // Value existed before with a different version; use variant key.
832  // Reflect purges to $key by requiring that this key value be newer.
833  $value = $this->doGetWithSetCallback(
834  'cache-variant:' . md5( $key ) . ":$version",
835  $ttl,
836  $callback,
837  // Regenerate value if not newer than $key
838  [ 'version' => null, 'minTime' => $asOf ] + $opts
839  );
840  }
841  } else {
842  $value = $this->doGetWithSetCallback( $key, $ttl, $callback, $opts );
843  }
844 
845  // Update the process cache if enabled
846  if ( $pcTTL >= 0 && $value !== false ) {
847  $this->procCache->set( $key, $value, $pcTTL );
848  }
849  }
850 
851  return $value;
852  }
853 
868  protected function doGetWithSetCallback( $key, $ttl, $callback, array $opts, &$asOf = null ) {
869  $lowTTL = isset( $opts['lowTTL'] ) ? $opts['lowTTL'] : min( self::LOW_TTL, $ttl );
870  $lockTSE = isset( $opts['lockTSE'] ) ? $opts['lockTSE'] : self::TSE_NONE;
871  $checkKeys = isset( $opts['checkKeys'] ) ? $opts['checkKeys'] : [];
872  $busyValue = isset( $opts['busyValue'] ) ? $opts['busyValue'] : null;
873  $minTime = isset( $opts['minTime'] ) ? $opts['minTime'] : 0.0;
874  $versioned = isset( $opts['version'] );
875 
876  // Get the current key value
877  $curTTL = null;
878  $cValue = $this->get( $key, $curTTL, $checkKeys, $asOf ); // current value
879  $value = $cValue; // return value
880 
881  // Determine if a regeneration is desired
882  if ( $value !== false
883  && $curTTL > 0
884  && $this->isValid( $value, $versioned, $asOf, $minTime )
885  && !$this->worthRefresh( $curTTL, $lowTTL )
886  ) {
887  return $value;
888  }
889 
890  // A deleted key with a negative TTL left must be tombstoned
891  $isTombstone = ( $curTTL !== null && $value === false );
892  // Assume a key is hot if requested soon after invalidation
893  $isHot = ( $curTTL !== null && $curTTL <= 0 && abs( $curTTL ) <= $lockTSE );
894  // Use the mutex if there is no value and a busy fallback is given
895  $checkBusy = ( $busyValue !== null && $value === false );
896  // Decide whether a single thread should handle regenerations.
897  // This avoids stampedes when $checkKeys are bumped and when preemptive
898  // renegerations take too long. It also reduces regenerations while $key
899  // is tombstoned. This balances cache freshness with avoiding DB load.
900  $useMutex = ( $isHot || ( $isTombstone && $lockTSE > 0 ) || $checkBusy );
901 
902  $lockAcquired = false;
903  if ( $useMutex ) {
904  // Acquire a datacenter-local non-blocking lock
905  if ( $this->cache->lock( $key, 0, self::LOCK_TTL ) ) {
906  // Lock acquired; this thread should update the key
907  $lockAcquired = true;
908  } elseif ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
909  // If it cannot be acquired; then the stale value can be used
910  return $value;
911  } else {
912  // Use the INTERIM value for tombstoned keys to reduce regeneration load.
913  // For hot keys, either another thread has the lock or the lock failed;
914  // use the INTERIM value from the last thread that regenerated it.
915  $wrapped = $this->cache->get( self::INTERIM_KEY_PREFIX . $key );
916  list( $value ) = $this->unwrap( $wrapped, microtime( true ) );
917  if ( $value !== false && $this->isValid( $value, $versioned, $asOf, $minTime ) ) {
918  $asOf = $wrapped[self::FLD_TIME];
919 
920  return $value;
921  }
922  // Use the busy fallback value if nothing else
923  if ( $busyValue !== null ) {
924  return is_callable( $busyValue ) ? $busyValue() : $busyValue;
925  }
926  }
927  }
928 
929  if ( !is_callable( $callback ) ) {
930  throw new InvalidArgumentException( "Invalid cache miss callback provided." );
931  }
932 
933  // Generate the new value from the callback...
934  $setOpts = [];
935  $value = call_user_func_array( $callback, [ $cValue, &$ttl, &$setOpts ] );
936  $asOf = microtime( true );
937  // When delete() is called, writes are write-holed by the tombstone,
938  // so use a special INTERIM key to pass the new value around threads.
939  if ( ( $isTombstone && $lockTSE > 0 ) && $value !== false && $ttl >= 0 ) {
940  $tempTTL = max( 1, (int)$lockTSE ); // set() expects seconds
941  $wrapped = $this->wrap( $value, $tempTTL, $asOf );
942  $this->cache->set( self::INTERIM_KEY_PREFIX . $key, $wrapped, $tempTTL );
943  }
944 
945  if ( $lockAcquired ) {
946  $this->cache->unlock( $key );
947  }
948 
949  if ( $value !== false && $ttl >= 0 ) {
950  // Update the cache; this will fail if the key is tombstoned
951  $setOpts['lockTSE'] = $lockTSE;
952  $this->set( $key, $value, $ttl, $setOpts );
953  }
954 
955  return $value;
956  }
957 
964  public function makeKey() {
965  return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
966  }
967 
974  public function makeGlobalKey() {
975  return call_user_func_array( [ $this->cache, __FUNCTION__ ], func_get_args() );
976  }
977 
982  final public function getLastError() {
983  if ( $this->lastRelayError ) {
984  // If the cache and the relayer failed, focus on the later.
985  // An update not making it to the relayer means it won't show up
986  // in other DCs (nor will consistent re-hashing see up-to-date values).
987  // On the other hand, if just the cache update failed, then it should
988  // eventually be applied by the relayer.
989  return $this->lastRelayError;
990  }
991 
992  $code = $this->cache->getLastError();
993  switch ( $code ) {
994  case BagOStuff::ERR_NONE:
995  return self::ERR_NONE;
997  return self::ERR_NO_RESPONSE;
999  return self::ERR_UNREACHABLE;
1000  default:
1001  return self::ERR_UNEXPECTED;
1002  }
1003  }
1004 
1008  final public function clearLastError() {
1009  $this->cache->clearLastError();
1010  $this->lastRelayError = self::ERR_NONE;
1011  }
1012 
1018  public function clearProcessCache() {
1019  $this->procCache->clear();
1020  }
1021 
1032  protected function relayPurge( $key, $ttl, $holdoff ) {
1033  $event = $this->cache->modifySimpleRelayEvent( [
1034  'cmd' => 'set',
1035  'key' => $key,
1036  'val' => 'PURGED:$UNIXTIME$:' . (int)$holdoff,
1037  'ttl' => max( $ttl, 1 ),
1038  'sbt' => true, // substitute $UNIXTIME$ with actual microtime
1039  ] );
1040 
1041  $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1042  if ( !$ok ) {
1043  $this->lastRelayError = self::ERR_RELAY;
1044  }
1045 
1046  return $ok;
1047  }
1048 
1055  protected function relayDelete( $key ) {
1056  $event = $this->cache->modifySimpleRelayEvent( [
1057  'cmd' => 'delete',
1058  'key' => $key,
1059  ] );
1060 
1061  $ok = $this->purgeRelayer->notify( $this->purgeChannel, $event );
1062  if ( !$ok ) {
1063  $this->lastRelayError = self::ERR_RELAY;
1064  }
1065 
1066  return $ok;
1067  }
1068 
1081  protected function worthRefresh( $curTTL, $lowTTL ) {
1082  if ( $curTTL >= $lowTTL ) {
1083  return false;
1084  } elseif ( $curTTL <= 0 ) {
1085  return true;
1086  }
1087 
1088  $chance = ( 1 - $curTTL / $lowTTL );
1089 
1090  return mt_rand( 1, 1e9 ) <= 1e9 * $chance;
1091  }
1092 
1102  protected function isValid( $value, $versioned, $asOf, $minTime ) {
1103  if ( $versioned && !isset( $value[self::VFLD_VERSION] ) ) {
1104  return false;
1105  } elseif ( $minTime > 0 && $asOf < $minTime ) {
1106  return false;
1107  }
1108 
1109  return true;
1110  }
1111 
1120  protected function wrap( $value, $ttl, $now ) {
1121  return [
1122  self::FLD_VERSION => self::VERSION,
1123  self::FLD_VALUE => $value,
1124  self::FLD_TTL => $ttl,
1125  self::FLD_TIME => $now
1126  ];
1127  }
1128 
1136  protected function unwrap( $wrapped, $now ) {
1137  // Check if the value is a tombstone
1138  $purge = self::parsePurgeValue( $wrapped );
1139  if ( $purge !== false ) {
1140  // Purged values should always have a negative current $ttl
1141  $curTTL = min( $purge[self::FLD_TIME] - $now, self::TINY_NEGATIVE );
1142  return [ false, $curTTL ];
1143  }
1144 
1145  if ( !is_array( $wrapped ) // not found
1146  || !isset( $wrapped[self::FLD_VERSION] ) // wrong format
1147  || $wrapped[self::FLD_VERSION] !== self::VERSION // wrong version
1148  ) {
1149  return [ false, null ];
1150  }
1151 
1152  $flags = isset( $wrapped[self::FLD_FLAGS] ) ? $wrapped[self::FLD_FLAGS] : 0;
1153  if ( ( $flags & self::FLG_STALE ) == self::FLG_STALE ) {
1154  // Treat as expired, with the cache time as the expiration
1155  $age = $now - $wrapped[self::FLD_TIME];
1156  $curTTL = min( -$age, self::TINY_NEGATIVE );
1157  } elseif ( $wrapped[self::FLD_TTL] > 0 ) {
1158  // Get the approximate time left on the key
1159  $age = $now - $wrapped[self::FLD_TIME];
1160  $curTTL = max( $wrapped[self::FLD_TTL] - $age, 0.0 );
1161  } else {
1162  // Key had no TTL, so the time left is unbounded
1163  $curTTL = INF;
1164  }
1165 
1166  return [ $wrapped[self::FLD_VALUE], $curTTL ];
1167  }
1168 
1174  protected static function prefixCacheKeys( array $keys, $prefix ) {
1175  $res = [];
1176  foreach ( $keys as $key ) {
1177  $res[] = $prefix . $key;
1178  }
1179 
1180  return $res;
1181  }
1182 
1188  protected static function parsePurgeValue( $value ) {
1189  if ( !is_string( $value ) ) {
1190  return false;
1191  }
1192  $segments = explode( ':', $value, 3 );
1193  if ( !isset( $segments[0] ) || !isset( $segments[1] )
1194  || "{$segments[0]}:" !== self::PURGE_VAL_PREFIX
1195  ) {
1196  return false;
1197  }
1198  if ( !isset( $segments[2] ) ) {
1199  // Back-compat with old purge values without holdoff
1200  $segments[2] = self::HOLDOFF_TTL;
1201  }
1202  return [
1203  self::FLD_TIME => (float)$segments[1],
1204  self::FLD_HOLDOFF => (int)$segments[2],
1205  ];
1206  }
1207 
1213  protected function makePurgeValue( $timestamp, $holdoff ) {
1214  return self::PURGE_VAL_PREFIX . (float)$timestamp . ':' . (int)$holdoff;
1215  }
1216 }
processCheckKeys(array $timeKeys, array $wrappedValues, $now)
set($key, $value, $ttl=0, array $opts=[])
Set the value of a key in cache.
string $purgeChannel
Purge channel name.
doGetWithSetCallback($key, $ttl, $callback, array $opts, &$asOf=null)
Do the actual I/O for getWithSetCallback() when needed.
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
const TTL_LAGGED
Max TTL to store keys when a data sourced is lagged.
const TINY_NEGATIVE
Tiny negative float to use when CTL comes up >= 0 due to clock skew.
the array() calling protocol came about after MediaWiki 1.4rc1.
const CHECK_KEY_TTL
Seconds to keep dependency purge keys around.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
clearProcessCache()
Clear the in-process caches; useful for testing.
static prefixCacheKeys(array $keys, $prefix)
unwrap($wrapped, $now)
Do not use this method outside WANObjectCache.
const MAX_COMMIT_DELAY
Max time expected to pass between delete() and DB commit finishing.
const TTL_UNCACHEABLE
Idiom for getWithSetCallback() callbacks to avoid calling set()
LoggerInterface $logger
EventRelayer $purgeRelayer
Bus that handles purge broadcasts.
const ERR_NO_RESPONSE
Definition: BagOStuff.php:75
touchCheckKey($key, $holdoff=self::HOLDOFF_TTL)
Purge a "check" key from all datacenters, invalidating keys that use it.
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:177
$value
const DEFAULT_PURGE_CHANNEL
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2588
const ERR_UNREACHABLE
Definition: BagOStuff.php:76
Multi-datacenter aware caching interface.
No-op class for publishing messages into a PubSub system.
getWithSetCallback($key, $ttl, $callback, array $opts=[])
Method to fetch/regenerate cache keys.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1629
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:Associative array mapping language codes to prefixed links of the form"language:title".&$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:1814
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
static newEmpty()
Get an instance that wraps EmptyBagOStuff.
const LOW_TTL
Default remaining TTL at which to consider pre-emptive regeneration.
getLastError()
Get the "last error" registered; clearLastError() should be called manually.
if($limit) $timestamp
$res
Definition: database.txt:21
__construct(array $params)
$params
const ERR_NONE
Possible values for getLastError()
Definition: BagOStuff.php:74
getCheckKeyTime($key)
Fetch the value of a timestamp "check" key.
const LOCK_TSE
Default time-since-expiry on a miss that makes a key "hot".
A BagOStuff object with no objects in it.
const HOLDOFF_NONE
Idiom for delete() for "no hold-off".
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
Definition: distributors.txt:9
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:776
isValid($value, $versioned, $asOf, $minTime)
Check whether $value is appropriately versioned and not older than $minTime (if set) ...
const VERSION
Cache format version number.
clearLastError()
Clear the "last error" registry.
resetCheckKey($key)
Delete a "check" key from all datacenters, invalidating keys that use it.
worthRefresh($curTTL, $lowTTL)
Check if a key should be regenerated (using random probability)
const HOLDOFF_TTL
Seconds to tombstone keys on delete()
Simple store for keeping values in an associative array for the current process.
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:35
relayPurge($key, $ttl, $holdoff)
Do the actual async bus purge of a key.
int $lastRelayError
ERR_* constant for the "last error" registry.
wrap($value, $ttl, $now)
Do not use this method outside WANObjectCache.
static parsePurgeValue($value)
const LOCK_TTL
Seconds to keep lock keys around.
makePurgeValue($timestamp, $holdoff)
getMulti(array $keys, &$curTTLs=[], array $checkKeys=[], array &$asOfs=[])
Fetch the value of several keys from cache.
relayDelete($key)
Do the actual async bus delete of a key.
Generic base class for storage interfaces.
$version
Definition: parserTests.php:94
const MAX_READ_LAG
Max replication+snapshot lag before applying TTL_LAGGED or disallowing set()
setLogger(LoggerInterface $logger)
const TSE_NONE
Idiom for getWithSetCallback() callbacks to 'lockTSE' logic.
HashBagOStuff $procCache
Script instance PHP cache.
BagOStuff $cache
The local datacenter cache.